SMS messages play a huge role in a person's life, and the confidentiality and integrity of said messages are of the highest priority to mobile carriers around the world. Due to this fact, many unlawful individuals and groups try and take advantange of the average consumer by flooding their inbox with spam, and while the majority of people successfully avoid it, there are people out there affected negatively by falling for false messages.
The data we selected is a compilation of 5574 SMS messages acquired from a variety of different sources, broken down in the following way: 452 of the messages came from the Grumbletext Web Site, 3375 of the messages were taken from the NUS SMS Corpus (database with legitimate message from the University of Singapore), 450 messages collected from Caroline Tag's PhD Thesis, and the last 1324 messages were from the SMS Spam Corpus v.0.1 Big.
Overall there were 4827 "ham" messages and 747 "spam" messages, and about 92,000 words.
This data was collected initially for studies on deciphering the differences between a spam or ham (legitimate) messages. Uses for this research can involve advanced spam filtering technology or improved data sets for machine learning programs. However, a slight problem with this data set, as with most localized language-based data sets, is that due to the relatively small area of sampling, there are a lot of regional data points (such as slang, acronyms, etc) that can be considering "useless" data if a much more generalized data set is wanted. For our specific project however, we are keeping all this data in order for us to analyze it and get a better understanding of our data. ___
import pandas as pd
import numpy as np
import requests
import re
import seaborn as sns
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
descriptors_url = 'https://raw.githubusercontent.com/LukeWoodSMU/TextAnalysis/master/data/SMSSpamCollection'
descriptors = requests.get(descriptors_url).text
texts = []
for line in descriptors.splitlines():
texts.append(line.rstrip().split("\t"))
After the first look at the data we noticed a lot of phone numbers. Since almost every number was unique we concluded that the numbers were irrelevant to consider as words. We considered grouping all number tokens into one token and analyze the presence of words, but we decided to first start by just removing the numbers.
# Remove numbers
texts = list(zip([a for a,b in texts], [re.sub('((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d', 'PHONE_NUMBER', b) for a,b in texts]))
Citation: regex from google search top results/stack overflow
import numpy as np
from keras.preprocessing import sequence
X = [x[1] for x in texts]
y = [x[0] for x in texts]
X = np.array(X)
print(type(X))
<class 'numpy.ndarray'>
import keras
y = [0 if y_ == "spam" else 1 for y_ in y]
y_ohe = keras.utils.to_categorical(y)
y_ohe
array([[ 0., 1.], [ 0., 1.], [ 1., 0.], ..., [ 0., 1.], [ 0., 1.], [ 0., 1.]])
We assign spam as a value of 0 and ham as a value of one so that we can use precision score to measure false positive scores.
import keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
NUM_TOP_WORDS = None
tokenizer = Tokenizer(num_words=NUM_TOP_WORDS)
tokenizer.fit_on_texts(X)
word_index = tokenizer.word_index
sequences = tokenizer.texts_to_sequences(X)
sequences = pad_sequences(sequences)
MAX_TEXT_LEN = len(sequences[0]) # maximum and minimum number of words
We tokenize and measure the max length of the text using keras' tokenizer.
We now have an embedding matrix for our word index.
Finally, we split our data into training data and testing data. We stratify the data on y_ohe to ensure that we get a fair representation of the spam and ham messages. We believe this to be appropriate because each model needs to see a fair number of both spam messages and ham messages to ensure it does not overtrain on either.
from sklearn.model_selection import train_test_split
# Split it into train / test subsets
X_train, X_test, y_train_ohe, y_test_ohe = train_test_split(sequences, y_ohe, test_size=0.2,
stratify=y_ohe,
random_state=42)
NUM_CLASSES = len(y_train_ohe[0])
NUM_CLASSES
2
We decided that due to our business understanding being that we can potentially create a spam filter, our largest cost should be false positives. It would be incredibly frustrating to have a real text filtered out so we should evaluate our models in accordance with this. To evaluate this, we must implement precision score which has been removed from keras. Luckily, the old code is available in a one of keras' old versions.
# Old version of keras had precision score, copied the code to re-implement it.
import keras.backend as K
def precision(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
Citation: old keras version
To avoid the need for training our own embedding layer which is incredibly computationally expensive, we load up a pretrained glove embedding.
EMBED_SIZE = 100
# the embed size should match the file you load glove from
embeddings_index = {}
f = open('GLOVE/glove.6B/glove.6B.100d.txt')
# save key/array pairs of the embeddings
# the key of the dictionary is the word, the array is the embedding
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
print('Found %s word vectors.' % len(embeddings_index))
# now fill in the matrix, using the ordering from the
# keras word tokenizer from before
embedding_matrix = np.zeros((len(word_index) + 1, EMBED_SIZE))
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix[i] = embedding_vector
print(embedding_matrix.shape)
Found 400000 word vectors. (9008, 100)
from keras.layers import Embedding
embedding_layer = Embedding(len(word_index) + 1,
EMBED_SIZE,
weights=[embedding_matrix],
input_length=MAX_TEXT_LEN,
trainable=False)
metrics=[precision,"accuracy"]
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
rnn = Sequential()
rnn.add(embedding_layer)
rnn.add(LSTM(100,dropout=0.2, recurrent_dropout=0.2))
rnn.add(Dense(NUM_CLASSES, activation='sigmoid'))
rnn.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
print(rnn.summary())
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_4 (Embedding) (None, 189, 100) 900800 _________________________________________________________________ lstm_4 (LSTM) (None, 100) 80400 _________________________________________________________________ dense_4 (Dense) (None, 2) 202 ================================================================= Total params: 981,402 Trainable params: 80,602 Non-trainable params: 900,800 _________________________________________________________________ None
rnn.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe), epochs=3, batch_size=64)
Train on 4459 samples, validate on 1115 samples Epoch 1/3 4459/4459 [==============================] - 41s - loss: 0.2196 - precision: 0.9709 - acc: 0.9222 - val_loss: 0.1293 - val_precision: 0.9937 - val_acc: 0.9543 Epoch 2/3 4459/4459 [==============================] - 37s - loss: 0.1170 - precision: 0.9884 - acc: 0.9630 - val_loss: 0.1125 - val_precision: 0.9919 - val_acc: 0.9596 Epoch 3/3 4459/4459 [==============================] - 39s - loss: 0.0973 - precision: 0.9919 - acc: 0.9650 - val_loss: 0.0984 - val_precision: 0.9847 - val_acc: 0.9614
<keras.callbacks.History at 0x126f3d668>
To begin, we will evaluate a network using an LSTM cell, a GRU cell, and a SimpleRNN cell. We will use a standard hyperparameter set to evaluate the results and decide which two architectures we want to explore in depth based on the results.
from keras.layers import LSTM, GRU, SimpleRNN
rnns = []
for func in [SimpleRNN, LSTM, GRU]:
rnn = Sequential()
rnn.add(embedding_layer)
rnn.add(func(100,dropout=0.2, recurrent_dropout=0.2))
rnn.add(Dense(NUM_CLASSES, activation='sigmoid'))
rnn.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
rnns.append(rnn)
for rnn, name in zip(rnns,['simple','lstm','gru']):
print('\nTesting Cell Type: ',name,'========')
rnn.fit(X_train, y_train_ohe, epochs=3, batch_size=64, validation_data=(X_test, y_test_ohe))
Testing Cell Type: simple ======== Train on 4459 samples, validate on 1115 samples Epoch 1/3 4459/4459 [==============================] - 8s - loss: 0.2695 - precision: 0.8955 - acc: 0.8955 - val_loss: 0.1736 - val_precision: 0.9533 - val_acc: 0.9381 Epoch 2/3 4459/4459 [==============================] - 9s - loss: 0.1652 - precision: 0.9512 - acc: 0.9401 - val_loss: 0.1433 - val_precision: 0.9682 - val_acc: 0.9516 Epoch 3/3 4459/4459 [==============================] - 7s - loss: 0.1422 - precision: 0.9616 - acc: 0.9477 - val_loss: 0.1757 - val_precision: 0.9587 - val_acc: 0.9444 Testing Cell Type: lstm ======== Train on 4459 samples, validate on 1115 samples Epoch 1/3 4459/4459 [==============================] - 39s - loss: 0.2070 - precision: 0.9618 - acc: 0.9291 - val_loss: 0.1340 - val_precision: 0.9818 - val_acc: 0.9525 Epoch 2/3 4459/4459 [==============================] - 40s - loss: 0.1172 - precision: 0.9878 - acc: 0.9599 - val_loss: 0.1165 - val_precision: 0.9786 - val_acc: 0.9596 Epoch 3/3 4459/4459 [==============================] - 37s - loss: 0.0969 - precision: 0.9885 - acc: 0.9641 - val_loss: 0.1051 - val_precision: 0.9832 - val_acc: 0.9578 Testing Cell Type: gru ======== Train on 4459 samples, validate on 1115 samples Epoch 1/3 4459/4459 [==============================] - 31s - loss: 0.2031 - precision: 0.9519 - acc: 0.9184 - val_loss: 0.1404 - val_precision: 0.9842 - val_acc: 0.9489 Epoch 2/3 4459/4459 [==============================] - 32s - loss: 0.1088 - precision: 0.9904 - acc: 0.9630 - val_loss: 0.0880 - val_precision: 0.9919 - val_acc: 0.9668 Epoch 3/3 4459/4459 [==============================] - 30s - loss: 0.0839 - precision: 0.9933 - acc: 0.9711 - val_loss: 0.1066 - val_precision: 0.9959 - val_acc: 0.9614
As we can see, the GRU model performs the best by a large margin. If we continue to train the GRU model it seems that we will get some really great results. We will try also try to find the best hyperparameters for the GRU model.
After we find the best GRU results we will use an LSTM and then measure the results of the LSTM.
dropouts=[.1,.2,.3]
recurrent_dropouts=[.1,.2,.3]
for dropout in dropouts:
for recurrent_dropout in recurrent_dropouts:
rnn = Sequential()
rnn.add(embedding_layer)
rnn.add(func(100,dropout=dropout, recurrent_dropout=recurrent_dropout))
rnn.add(Dense(NUM_CLASSES, activation='sigmoid'))
rnn.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
print("Hyper Paramater Set:\n\tdropout=%.1f\n\trecurrent_dropout=%.1f" % (dropout,recurrent_dropout))
rnn.fit(X_train,y_train_ohe,epochs=3, batch_size=64, validation_data=(X_train,y_train_ohe))
Hyper Paramater Set: dropout=0.1 recurrent_dropout=0.1 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 35s - loss: 0.2053 - precision: 0.9481 - acc: 0.9161 - val_loss: 0.1584 - val_precision: 0.9821 - val_acc: 0.9424 Epoch 2/3 4459/4459 [==============================] - 35s - loss: 0.0966 - precision: 0.9941 - acc: 0.9677 - val_loss: 0.0613 - val_precision: 0.9964 - val_acc: 0.9803 Epoch 3/3 4459/4459 [==============================] - 32s - loss: 0.0764 - precision: 0.9958 - acc: 0.9749 - val_loss: 0.0489 - val_precision: 0.9970 - val_acc: 0.9874 Hyper Paramater Set: dropout=0.1 recurrent_dropout=0.2 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 37s - loss: 0.1912 - precision: 0.9709 - acc: 0.9276 - val_loss: 0.0929 - val_precision: 0.9941 - val_acc: 0.9713 Epoch 2/3 4459/4459 [==============================] - 36s - loss: 0.0990 - precision: 0.9923 - acc: 0.9657 - val_loss: 0.0655 - val_precision: 0.9956 - val_acc: 0.9807 Epoch 3/3 4459/4459 [==============================] - 34s - loss: 0.0736 - precision: 0.9944 - acc: 0.9740 - val_loss: 0.0574 - val_precision: 0.9955 - val_acc: 0.9800 Hyper Paramater Set: dropout=0.1 recurrent_dropout=0.3 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 35s - loss: 0.2065 - precision: 0.9516 - acc: 0.9155 - val_loss: 0.1964 - val_precision: 0.9757 - val_acc: 0.9204 Epoch 2/3 4459/4459 [==============================] - 35s - loss: 0.1086 - precision: 0.9851 - acc: 0.9632 - val_loss: 0.1534 - val_precision: 0.9835 - val_acc: 0.9392 Epoch 3/3 4459/4459 [==============================] - 42s - loss: 0.0839 - precision: 0.9914 - acc: 0.9722 - val_loss: 0.0536 - val_precision: 0.9954 - val_acc: 0.9823 Hyper Paramater Set: dropout=0.2 recurrent_dropout=0.1 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 38s - loss: 0.2040 - precision: 0.9561 - acc: 0.9202 - val_loss: 0.1101 - val_precision: 0.9899 - val_acc: 0.9612 Epoch 2/3 4459/4459 [==============================] - 36s - loss: 0.1056 - precision: 0.9898 - acc: 0.9634 - val_loss: 0.0653 - val_precision: 0.9957 - val_acc: 0.9765 Epoch 3/3 4459/4459 [==============================] - 36s - loss: 0.0864 - precision: 0.9936 - acc: 0.9677 - val_loss: 0.0653 - val_precision: 0.9945 - val_acc: 0.9765 Hyper Paramater Set: dropout=0.2 recurrent_dropout=0.2 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 39s - loss: 0.2279 - precision: 0.9341 - acc: 0.9054 - val_loss: 0.0955 - val_precision: 0.9936 - val_acc: 0.9682 Epoch 2/3 4459/4459 [==============================] - 40s - loss: 0.1146 - precision: 0.9885 - acc: 0.9601 - val_loss: 0.0695 - val_precision: 0.9954 - val_acc: 0.9742 Epoch 3/3 4459/4459 [==============================] - 40s - loss: 0.0802 - precision: 0.9936 - acc: 0.9738 - val_loss: 0.0523 - val_precision: 0.9955 - val_acc: 0.9832 Hyper Paramater Set: dropout=0.2 recurrent_dropout=0.3 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 43s - loss: 0.2062 - precision: 0.9600 - acc: 0.9186 - val_loss: 0.0998 - val_precision: 0.9932 - val_acc: 0.9688 Epoch 2/3 4459/4459 [==============================] - 40s - loss: 0.1090 - precision: 0.9906 - acc: 0.9623 - val_loss: 0.0795 - val_precision: 0.9914 - val_acc: 0.9704 Epoch 3/3 4459/4459 [==============================] - 41s - loss: 0.0895 - precision: 0.9927 - acc: 0.9693 - val_loss: 0.0608 - val_precision: 0.9940 - val_acc: 0.9796 Hyper Paramater Set: dropout=0.3 recurrent_dropout=0.1 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 37s - loss: 0.2147 - precision: 0.9446 - acc: 0.9137 - val_loss: 0.0979 - val_precision: 0.9917 - val_acc: 0.9657 Epoch 2/3 4459/4459 [==============================] - 38s - loss: 0.1082 - precision: 0.9877 - acc: 0.9639 - val_loss: 0.0852 - val_precision: 0.9920 - val_acc: 0.9686 Epoch 3/3 4459/4459 [==============================] - 36s - loss: 0.0911 - precision: 0.9884 - acc: 0.9679 - val_loss: 0.0593 - val_precision: 0.9942 - val_acc: 0.9830 Hyper Paramater Set: dropout=0.3 recurrent_dropout=0.2 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 37s - loss: 0.2327 - precision: 0.9352 - acc: 0.9031 - val_loss: 0.1011 - val_precision: 0.9906 - val_acc: 0.9652 Epoch 2/3 4459/4459 [==============================] - 39s - loss: 0.1179 - precision: 0.9878 - acc: 0.9578 - val_loss: 0.0704 - val_precision: 0.9946 - val_acc: 0.9756 Epoch 3/3 4459/4459 [==============================] - 36s - loss: 0.0892 - precision: 0.9921 - acc: 0.9693 - val_loss: 0.0549 - val_precision: 0.9947 - val_acc: 0.9821 Hyper Paramater Set: dropout=0.3 recurrent_dropout=0.3 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 37s - loss: 0.2215 - precision: 0.9459 - acc: 0.9146 - val_loss: 0.1023 - val_precision: 0.9925 - val_acc: 0.9670 Epoch 2/3 4459/4459 [==============================] - 36s - loss: 0.1258 - precision: 0.9850 - acc: 0.9576 - val_loss: 0.0773 - val_precision: 0.9944 - val_acc: 0.9735 Epoch 3/3 4459/4459 [==============================] - 35s - loss: 0.1040 - precision: 0.9881 - acc: 0.9630 - val_loss: 0.0796 - val_precision: 0.9937 - val_acc: 0.9751
As we can see, with dropout and recurrent dropout at .1 we get some really great results; with accuracy getting as high as 98.6%. This is ridiculously high. The model gets .997 precision and .98 accuracy on the validation set with these hyperparameters.
We actually get a similar precision score in a few sets of hyperparameters, but we get a higher accuracy with the .1 and .1 set so this is our most effective model.
best_model = Sequential()
best_model.add(embedding_layer)
best_model.add(GRU(100,dropout=.1, recurrent_dropout=.1))
best_model.add(Dense(NUM_CLASSES, activation='sigmoid'))
best_model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
best_model.fit(X_train,y_train_ohe,epochs=10, batch_size=64, validation_data=(X_train,y_train_ohe))
Train on 4459 samples, validate on 4459 samples Epoch 1/10 4459/4459 [==============================] - 36s - loss: 0.2041 - precision: 0.9385 - acc: 0.9208 - val_loss: 0.0910 - val_precision: 0.9901 - val_acc: 0.9688 Epoch 2/10 4459/4459 [==============================] - 34s - loss: 0.0957 - precision: 0.9896 - acc: 0.9666 - val_loss: 0.0603 - val_precision: 0.9927 - val_acc: 0.9760 Epoch 3/10 4459/4459 [==============================] - 38s - loss: 0.0679 - precision: 0.9909 - acc: 0.9767 - val_loss: 0.0468 - val_precision: 0.9959 - val_acc: 0.9830 Epoch 4/10 4459/4459 [==============================] - 38s - loss: 0.0566 - precision: 0.9931 - acc: 0.9823 - val_loss: 0.0377 - val_precision: 0.9961 - val_acc: 0.9886 Epoch 5/10 4459/4459 [==============================] - 36s - loss: 0.0444 - precision: 0.9952 - acc: 0.9839 - val_loss: 0.0329 - val_precision: 0.9966 - val_acc: 0.9908 Epoch 6/10 4459/4459 [==============================] - 35s - loss: 0.0367 - precision: 0.9952 - acc: 0.9888 - val_loss: 0.0349 - val_precision: 0.9970 - val_acc: 0.9901 Epoch 7/10 4459/4459 [==============================] - 36s - loss: 0.0310 - precision: 0.9962 - acc: 0.9897 - val_loss: 0.0170 - val_precision: 0.9972 - val_acc: 0.9955 Epoch 8/10 4459/4459 [==============================] - 37s - loss: 0.0264 - precision: 0.9967 - acc: 0.9924 - val_loss: 0.0186 - val_precision: 0.9963 - val_acc: 0.9946 Epoch 9/10 4459/4459 [==============================] - 41s - loss: 0.0226 - precision: 0.9972 - acc: 0.9926 - val_loss: 0.0145 - val_precision: 0.9975 - val_acc: 0.9951 Epoch 10/10 4459/4459 [==============================] - 38s - loss: 0.0204 - precision: 0.9974 - acc: 0.9944 - val_loss: 0.0110 - val_precision: 0.9986 - val_acc: 0.9962
<keras.callbacks.History at 0x12a7f0b70>
Now that we know we can get results as high as 99.5% accuracy and 99.8% precision with the GRU network we will try to see how high we can get our LSTM's score.
dropouts=[.1,.2,.3]
recurrent_dropouts=[.1,.2,.3]
for dropout in dropouts:
for recurrent_dropout in recurrent_dropouts:
rnn = Sequential()
rnn.add(embedding_layer)
rnn.add(LSTM(100,dropout=dropout, recurrent_dropout=recurrent_dropout))
rnn.add(Dense(NUM_CLASSES, activation='sigmoid'))
rnn.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
print("Hyper Paramater Set:\n\tdropout=%.1f\n\trecurrent_dropout=%.1f" % (dropout,recurrent_dropout))
rnn.fit(X_train,y_train_ohe,epochs=3, batch_size=64, validation_data=(X_train,y_train_ohe))
Hyper Paramater Set: dropout=0.1 recurrent_dropout=0.1 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 48s - loss: 0.1968 - precision: 0.9571 - acc: 0.9278 - val_loss: 0.1018 - val_precision: 0.9885 - val_acc: 0.9639 Epoch 2/3 4459/4459 [==============================] - 47s - loss: 0.1085 - precision: 0.9844 - acc: 0.9637 - val_loss: 0.0695 - val_precision: 0.9896 - val_acc: 0.9778 Epoch 3/3 4459/4459 [==============================] - 48s - loss: 0.0815 - precision: 0.9880 - acc: 0.9684 - val_loss: 0.0582 - val_precision: 0.9899 - val_acc: 0.9794 Hyper Paramater Set: dropout=0.1 recurrent_dropout=0.2 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 51s - loss: 0.1928 - precision: 0.9668 - acc: 0.9289 - val_loss: 0.1059 - val_precision: 0.9903 - val_acc: 0.9652 Epoch 2/3 4459/4459 [==============================] - 46s - loss: 0.1089 - precision: 0.9896 - acc: 0.9610 - val_loss: 0.0720 - val_precision: 0.9902 - val_acc: 0.9762 Epoch 3/3 4459/4459 [==============================] - 47s - loss: 0.0844 - precision: 0.9910 - acc: 0.9704 - val_loss: 0.0635 - val_precision: 0.9944 - val_acc: 0.9800 Hyper Paramater Set: dropout=0.1 recurrent_dropout=0.3 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 48s - loss: 0.1962 - precision: 0.9694 - acc: 0.9282 - val_loss: 0.0978 - val_precision: 0.9917 - val_acc: 0.9682 Epoch 2/3 4459/4459 [==============================] - 46s - loss: 0.1143 - precision: 0.9885 - acc: 0.9610 - val_loss: 0.0911 - val_precision: 0.9924 - val_acc: 0.9682 Epoch 3/3 4459/4459 [==============================] - 47s - loss: 0.0928 - precision: 0.9881 - acc: 0.9693 - val_loss: 0.0719 - val_precision: 0.9924 - val_acc: 0.9765 Hyper Paramater Set: dropout=0.2 recurrent_dropout=0.1 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 48s - loss: 0.2002 - precision: 0.9681 - acc: 0.9267 - val_loss: 0.1015 - val_precision: 0.9937 - val_acc: 0.9634 Epoch 2/3 4459/4459 [==============================] - 46s - loss: 0.1122 - precision: 0.9907 - acc: 0.9576 - val_loss: 0.0860 - val_precision: 0.9922 - val_acc: 0.9702 Epoch 3/3 4459/4459 [==============================] - 45s - loss: 0.0911 - precision: 0.9921 - acc: 0.9691 - val_loss: 0.0613 - val_precision: 0.9951 - val_acc: 0.9780 Hyper Paramater Set: dropout=0.2 recurrent_dropout=0.2 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 45s - loss: 0.2044 - precision: 0.9493 - acc: 0.9255 - val_loss: 0.1569 - val_precision: 0.9764 - val_acc: 0.9390 Epoch 2/3 4459/4459 [==============================] - 44s - loss: 0.1201 - precision: 0.9855 - acc: 0.9581 - val_loss: 0.0784 - val_precision: 0.9938 - val_acc: 0.9726 Epoch 3/3 4459/4459 [==============================] - 44s - loss: 0.0966 - precision: 0.9900 - acc: 0.9661 - val_loss: 0.1216 - val_precision: 0.9829 - val_acc: 0.9581 Hyper Paramater Set: dropout=0.2 recurrent_dropout=0.3 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 47s - loss: 0.2170 - precision: 0.9472 - acc: 0.9141 - val_loss: 0.1214 - val_precision: 0.9869 - val_acc: 0.9583 Epoch 2/3 4459/4459 [==============================] - 45s - loss: 0.1127 - precision: 0.9882 - acc: 0.9637 - val_loss: 0.0759 - val_precision: 0.9936 - val_acc: 0.9744 Epoch 3/3 4459/4459 [==============================] - 46s - loss: 0.1013 - precision: 0.9885 - acc: 0.9625 - val_loss: 0.0647 - val_precision: 0.9942 - val_acc: 0.9778 Hyper Paramater Set: dropout=0.3 recurrent_dropout=0.1 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 47s - loss: 0.2159 - precision: 0.9578 - acc: 0.9161 - val_loss: 0.1177 - val_precision: 0.9861 - val_acc: 0.9581 Epoch 2/3 4459/4459 [==============================] - 46s - loss: 0.1269 - precision: 0.9877 - acc: 0.9547 - val_loss: 0.0850 - val_precision: 0.9911 - val_acc: 0.9706 Epoch 3/3 4459/4459 [==============================] - 48s - loss: 0.0997 - precision: 0.9906 - acc: 0.9650 - val_loss: 0.0646 - val_precision: 0.9916 - val_acc: 0.9771 Hyper Paramater Set: dropout=0.3 recurrent_dropout=0.2 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 43s - loss: 0.2153 - precision: 0.9373 - acc: 0.9134 - val_loss: 0.1142 - val_precision: 0.9834 - val_acc: 0.9578 Epoch 2/3 4459/4459 [==============================] - 45s - loss: 0.1225 - precision: 0.9840 - acc: 0.9558 - val_loss: 0.1138 - val_precision: 0.9863 - val_acc: 0.9605 Epoch 3/3 4459/4459 [==============================] - 48s - loss: 0.1009 - precision: 0.9899 - acc: 0.9639 - val_loss: 0.0678 - val_precision: 0.9941 - val_acc: 0.9765 Hyper Paramater Set: dropout=0.3 recurrent_dropout=0.3 Train on 4459 samples, validate on 4459 samples Epoch 1/3 4459/4459 [==============================] - 51s - loss: 0.2087 - precision: 0.9629 - acc: 0.9190 - val_loss: 0.1086 - val_precision: 0.9845 - val_acc: 0.9590 Epoch 2/3 4459/4459 [==============================] - 44s - loss: 0.1292 - precision: 0.9855 - acc: 0.9547 - val_loss: 0.1018 - val_precision: 0.9875 - val_acc: 0.9637 Epoch 3/3 4459/4459 [==============================] - 49s - loss: 0.1055 - precision: 0.9885 - acc: 0.9617 - val_loss: 0.1314 - val_precision: 0.9876 - val_acc: 0.9495
best_lstm = Sequential()
best_lstm.add(embedding_layer)
best_lstm.add(LSTM(100,dropout=.1, recurrent_dropout=.2))
best_lstm.add(Dense(NUM_CLASSES, activation='sigmoid'))
best_lstm.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
%%time
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.metrics import confusion_matrix, precision_score
sss = StratifiedShuffleSplit(n_splits=3)
gru_scores = []
gru_cms = []
lstm_scores = []
lstm_cms = []
split_num = 1
for train_index, test_index in sss.split(sequences, y_ohe):
print('Split #{}'.format(split_num))
split_num += 1
X_train, X_test = sequences[train_index], sequences[test_index]
y_train_ohe, y_test_ohe = y_ohe[train_index], y_ohe[test_index]
# one hot decode for scoring
y_test = [list(x).index(1.0) for x in list(y_test_ohe)]
best_model.fit(X_train,y_train_ohe,epochs=3,
batch_size=64,validation_data=(X_train,y_train_ohe),verbose=0)
y_hat = best_model.predict(X_test)
# one hot decode for scoring
y_hat = np.array([[0,1] if np.argmax(x) == 1 else [1,0] for x in y_hat]).astype(float)
y_hat = [list(x).index(1.0) for x in list(y_hat)]
gru_scores.append(precision_score(y_test, y_hat))
gru_cms.append(confusion_matrix(y_test, y_hat))
print(gru_scores[-1])
print(gru_cms[-1])
best_lstm.fit(X_train,y_train_ohe,epochs=3,
batch_size=64,validation_data=(X_train,y_train_ohe),verbose=0)
y_hat = best_lstm.predict(X_test)
# one hot decode for scoring
y_hat = np.array([[0,1] if np.argmax(x) == 1 else [1,0] for x in y_hat]).astype(float)
y_hat = [list(x).index(1.0) for x in list(y_hat)]
lstm_scores.append(precision_score(y_test, y_hat))
lstm_cms.append(confusion_matrix(y_test, y_hat))
print(lstm_scores[-1])
print(lstm_cms[-1])
Split #1 0.995780590717 [[ 84 2] [ 0 472]] 0.985386221294 [[ 79 7] [ 0 472]] Split #2 1.0 [[ 84 0] [ 0 474]] 0.991631799163 [[ 80 4] [ 0 474]] Split #3 1.0 [[ 70 0] [ 0 488]] 0.993890020367 [[ 67 3] [ 0 488]] CPU times: user 45min 55s, sys: 5min 6s, total: 51min 1s Wall time: 16min 21s
# Plot bar graphs
bar_width = 0.20
index = np.arange(3)
opacity=0.4
plt.bar(index, gru_scores, bar_width, align='center',
color='b', label='GRU', alpha=opacity)
plt.bar(index + bar_width, lstm_scores, bar_width,
align='center', color='r', label='LSTM', alpha=opacity)
plt.title('GRU vs LSTM (precision score)')
plt.legend()
plt.tight_layout()
plt.show()
Both models perform extremely well, however the GRU model performed just a bit better, even getting a perfect score on 2 of the 3 splits.
By looking at heatmaps of the confusion matrices we can get a more granular look into how our models classify each class.
# Plot heatmap
labels = ['Spam', 'Ham']
gru_cm_avg = np.zeros((2,2))
for cm in gru_cms:
# turn cm into percentages
totals = np.repeat(np.sum(cm, axis=1), 2, axis=0).reshape(2,2)
cm_ = cm / totals / 3
gru_cm_avg = np.sum([gru_cm_avg, cm_], axis=0)
sns.heatmap(gru_cm_avg, annot=True, xticklabels=labels, yticklabels=labels)
plt.title('Heatmap of GRU')
<matplotlib.text.Text at 0x7f209069db38>
# Plot heatmap
lstm_cm_avg = np.zeros((2,2))
for cm in lstm_cms:
# turn cm into percentages
totals = np.repeat(np.sum(cm, axis=1), 2, axis=0).reshape(2,2)
cm_ = cm / totals / 3
lstm_cm_avg = np.sum([lstm_cm_avg, cm_], axis=0)
sns.heatmap(lstm_cm_avg, annot=True, xticklabels=labels, yticklabels=labels)
plt.title('Heatmap of lstm')
<matplotlib.text.Text at 0x7f2090589748>
From the heatmaps we can see that ham gets classified perfectly using both models, however our GRU model scores much better than the LSTM when classifying spam instances.
We thought it could be interesting to compare the generalized NLTK tokenizer to the keras tokenizer. We decided to compare them using basic LSTM networks.
from nltk.tokenize import word_tokenize
X_nltk = [word_tokenize(x) for x in X]
encoder = {}
counter = 0
def encode_sentence(seq):
global encoder, counter
fseq = []
for x in seq:
if x not in encoder:
encoder[x] = counter
counter+=1
fseq.append(encoder[x])
return fseq
X_nltk = [encode_sentence(x) for x in X]
X_nltk = pad_sequences(X_nltk, maxlen=None)
embedding_layer = Embedding(len(word_index) + 1,
EMBED_SIZE,
weights=[embedding_matrix],
input_length=len(X_nltk[0]),
trainable=False)
rnn = Sequential()
rnn.add(embedding_layer)
rnn.add(LSTM(100,dropout=0.2, recurrent_dropout=0.2))
rnn.add(Dense(NUM_CLASSES, activation='sigmoid'))
rnn.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
print(rnn.summary())
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_3 (Embedding) (None, 910, 100) 862100 _________________________________________________________________ lstm_12 (LSTM) (None, 100) 80400 _________________________________________________________________ dense_12 (Dense) (None, 2) 202 ================================================================= Total params: 942,702.0 Trainable params: 80,602.0 Non-trainable params: 862,100.0 _________________________________________________________________ None
X_train, X_test, y_train_ohe, y_test_ohe = train_test_split(X_nltk, y_ohe, test_size=0.2,
stratify=y_ohe,
random_state=42)
rnn.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe), epochs=3, batch_size=64)
Train on 4459 samples, validate on 1115 samples Epoch 1/3
I really liked being able to easily use glove embeddings with keras so I published a package to PyPi for it. It's available under kerasglove and removes the need for a lot of the code in the notebook. Here is a sample usage of it:
from kerasglove import GloveEmbedding
EMBED_SIZE=100
metrics = ['accuracy',precision]
embed_layer = GloveEmbedding(
EMBED_SIZE,
MAX_TEXT_LEN,
word_index)
embed_layer
<keras.layers.embeddings.Embedding at 0x1295a3518>
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from kerasglove import GloveEmbedding
rnn = Sequential()
rnn.add(GloveEmbedding(EMBED_SIZE,
MAX_TEXT_LEN,
word_index))
rnn.add(GRU(100,dropout=0.2, recurrent_dropout=0.2))
rnn.add(Dense(NUM_CLASSES, activation='sigmoid'))
rnn.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=metrics)
print(rnn.summary())
rnn.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe), epochs=3, batch_size=64)
As we can see, this is far easier to construct a network with a pre trained GloVe emebedding than doing it manually.
The full source is here: https://github.com/LukeWoodSMU/KerasGlove