-
Notifications
You must be signed in to change notification settings - Fork 1
/
classifyingTextNUMBERS.py
163 lines (108 loc) · 5.64 KB
/
classifyingTextNUMBERS.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#written by Viktor Zenkov in 2018
#This file was used for both the text and the hex models, with the only difference being that line 69 had an input of true for the text model and false for the hex model.
from __future__ import print_function
from __future__ import absolute_import
import sys
import numpy as np
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
set_random_seed(2)
import matplotlib.pyplot as plt
import math
import time
import datetime
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding
from keras.layers import LSTM, Dropout, Activation
from keras.utils import to_categorical, print_summary
from keras.callbacks import EarlyStopping
from sklearn.metrics import confusion_matrix
import itertools
print('sys.argv[0]: {0!r}'.format(sys.argv[0]))
print('sys.path[0]: {0!r}'.format(sys.path[0]))
#this plots a confusion matrix
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion Matrix', cmap=plt.cm.Blues):
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title, fontsize=30)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks,classes, rotation=45,fontsize=22)
plt.yticks(tick_marks,classes, fontsize=22)
fmt = '.2f'
thresh = cm.max()/2.
for i,j in itertools.product(range(cm.shape[0]),range(cm.shape[1])):
plt.text(j, i, format(cm[i,j],fmt),horizontalalignment="center",color='white' if cm[i,j]>thresh else 'black')
plt.ylabel('True label', fontsize=25)
plt.xlabel('Predicted label', fontsize=25)
import classifyingFunctions
max_features = 5000 #this is the number of unique integers we will keep.
maxlen = 15000 # cut texts after this number of words (among top max_features most common words), used in pad_sequences (right after load data, before any modeling)
batch_size = 32
print('Loading data...')
#num_words' default is None, which is taken to mean that all unique integers should be kept.
(x_train, y_train), (x_test, y_test) = classifyingFunctions.load_data(num_words=max_features,numOrHex=True) #all integers greater than max_features get turned into 2's, so there's max_features number of unique "words"
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')
print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)
y_test_ld = y_test
#We have classes from 1 to 9, which is 9 classes, but to_categorical will make an array with spots from 0 to max_class, so we subtract 1 such that our classes are 0 to 8 and we can use 9 classes.
y_train -= 1
y_test -= 1
y_train = to_categorical(y_train, 9)
y_test = to_categorical(y_test, 9)
print('y_train shape:', y_train.shape)
print('y_test shape:', y_test.shape)
print('Build model...')
model = Sequential()
model.add(Embedding(max_features, 128)) #first argument - "the size of the vocabulary". #second argument is dimension of dense embedding (dimension of each vector "replacing" each integer)
print (model.output_shape)
#first argument of LSTM (150 here) is the dimensionality of the output space, the number of memory cells/neurons. The input shape is 3D : (batch/samples row, timesteps (=max len) past observations, dimension of the embedding vector (someone called it the features column)).LSTM is recurrent neural network
model.add(LSTM(150, dropout=0.05, recurrent_dropout=0.05))
print (model.output_shape)
#a dense/fully connected layer - each neuron is connected to all the neurons on the next layer.
#Since this is the last layer, the first input is the number of classes, 9. The softmax forms the probabilities.
model.add(Dense(9, activation='softmax'))
print (model.output_shape)
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
es = EarlyStopping(monitor="val_acc",min_delta=0.005,patience=20,mode='max') #meaning of this: when val_acc stops increasing by more than min_delta, we stop at current epoch. patience had default of 0. patience is the number of epochs with no improvement after which training will be stopped. the definition of improvement seems to be our min delta rule. We wonder if this will make less variation in accuracies when running lots of identical jobs
print('Train...')
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=26,
validation_split=0.15, callbacks=[es])
model.save('model'+str(datetime.date.today())+str(math.floor(time.time()))+'.h5')
score, acc = model.evaluate(x_test, y_test,
batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)
#the rest of this is for the confusion matrix
y_probs = model.predict(x_test)
#this block of code makes a 1D array of predicted labels, which is an input to the confusion matrix
y_pred_ld = []
for i in range(0, len(y_probs)):
probs = y_probs[i]
predicted_index = np.argmax(probs)
y_pred_ld.append(predicted_index)
cnf_matrix = confusion_matrix(y_test_ld, y_pred_ld)
print(cnf_matrix)
cnf_matrix = cnf_matrix.astype('float') / cnf_matrix.sum(axis=1)[:, np.newaxis]
print(cnf_matrix)
print_summary(model)
#plt.subplot(221)
#plot_confusion_matrix(cnf_matrix,classes=range(1,10),normalize=False,title="Confusion matrix")
#plt.subplot(222)
#plt.show()
#plot_confusion_matrix(cnf_matrix,classes=range(0,10),normalize=True,title="Confusion matrix")
#plt.show()
print("end of file")