-
Notifications
You must be signed in to change notification settings - Fork 0
/
model_cnn.py
149 lines (132 loc) · 5.21 KB
/
model_cnn.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
import pickle
import os
import numpy as np
import pandas as pd
import math
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from sklearn.metrics import *
batch_size = 2048
num_files = 2
embedding_size = 300
question_size = 30
max_features = 40000
#activ = 'relu'
activ = 'tanh'
def get_concatenated_embeddings(temp_df):
# print("tdf", temp_df.shape)
zero_embeddings = np.zeros(embedding_size)
truncated_df = temp_df[:question_size]
# print(truncated_df.shape)
# print(len(truncated_df),len(truncated_df[0]))
# print(type([zero_embeddings]*(question_size-len(truncated_df))))
# print(np.array([zero_embeddings]*(question_size - len(truncated_df))).shape)
if(len(truncated_df)!=30):
truncated_df = np.concatenate((truncated_df, np.array([zero_embeddings]*(question_size- len(truncated_df)))))
# truncated_df.append(zero_embeddings*(question_size - len(truncated_df)))
return truncated_df
def batch_gen(n_batches,y,all_embeddings):
# print("bg")
while True:
for i in range(n_batches):
# print("for loop")
embeddings_list = all_embeddings[i*batch_size:(i+1)*batch_size]
# print("el",embeddings_list.shape,all_embeddings.shape,embeddings_list[0].shape)
concat_embed_ques = np.array([get_concatenated_embeddings(ques) for ques in embeddings_list])
#print(i,concat_embed_ques.shape)
yield concat_embed_ques, np.array(y[i*batch_size:(i+1)*batch_size])
train_df = pd.read_csv("train.csv")
test_df = pd.read_csv("test.csv")
all_embeddings = pickle.load(open("merged_embeddings_train","rb"))
#all_embeddings_test = pickle.load(open("merged_embeddings_test","rb"))
#print(all_embeddings.shape, all_embeddings[0].shape)
#print(type(all_embeddings),type(all_embeddings[0]))
all_embeddings_train, all_embeddings_test,all_y_train,all_y_test = train_test_split(all_embeddings, train_df["target"][0:all_embeddings.shape[0]], test_size = 0.30, random_state = 42)
embeddings_train,embeddings_val,y_train,y_val= train_test_split(all_embeddings_train,all_y_train,test_size=0.20)
n_batches = math.ceil(len(y_train)/batch_size)
print("train set",len(y_train))
print("test set",len(all_y_test))
print("val set",len(y_val))
bg = batch_gen(n_batches,y_train,embeddings_train)
val_vects = np.array([get_concatenated_embeddings(val_emb) for val_emb in embeddings_val][:3000])
val_y = np.array(y_val[:3000])
from keras.models import Sequential
from keras.layers import *
filters = 128
model = Sequential()
model.add(Conv1D(filters,1,activation = activ, input_shape = (30,300)))
model.add(Dropout(0.1))
model.add(Conv1D(filters,2,activation = activ))
model.add(Dropout(0.1))
model.add(Conv1D(filters,3,activation = activ))
model.add(Dropout(0.1))
model.add(Conv1D(filters,5,activation = activ))
model.add(Dropout(0.1))
model.add(GlobalAveragePooling1D())
model.add(Dropout(0.3))
model.add(Dense(128,activation = activ))
model.add(Dense(1,activation= 'sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
history = model.fit_generator(bg, epochs=5,
steps_per_epoch=1000,
validation_data=(val_vects, val_y),
verbose=True)
#test_vects = np.array([get_concatenated_embeddings(test_emb) for test_emb in all_embeddings_test])
#test_y = np.array(y_test[:3000])
test_gen=batch_gen(n_batches,all_y_test,all_embeddings_test)
scores=model.evaluate_generator(test_gen,steps=25,verbose=1)
print("Accuracy", scores[1])
import matplotlib.pyplot as plt
batch_size = 30000
test_whole = batch_gen(1, all_y_test,all_embeddings_test)
pred_prob=model.predict_generator(test_whole,steps=1,verbose=1)
pred_y = pred_prob > 0.5
print("F1 score: ",f1_score(all_y_test[:batch_size],pred_y))
print("Confusion_matrix:\n",confusion_matrix(all_y_test[:batch_size],pred_y))
precision, recall, _ = precision_recall_curve(all_y_test[:batch_size],pred_prob)
plt.figure()
plt.title("Precision Recall Curve")
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.plot([0, 1], [0.5, 0.5], linestyle='--')
# plot the precision-recall curve for the model
plt.plot(recall, precision, marker='.')
# show the plot
plt.show()
plt.savefig('cnn_prc.png')
print("roc curve \n")
fpr, tpr, threshold = roc_curve(all_y_test[:batch_size],pred_prob)
roc_auc = roc_auc_score(all_y_test[:batch_size],pred_prob)
plt.figure()
plt.title("Receiver Operating Characeristic")
plt.plot(fpr,tpr,'b', label = 'AUC = %0.2f' %roc_auc)
plt.legend(loc = 'lower right')
plt.plot([0,1], [0,1], 'r--')
plt.xlim([0,1])
plt.ylim([0,1])
plt.ylabel('True positive rate')
plt.xlabel('False positive rate')
plt.show()
plt.savefig('cnn_roc.png')
# summarize history for accuracy
plt.figure()
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
plt.savefig('cnn_acc_history.png')
# summarize history for loss
plt.figure()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
plt.savefig('cnn_loss_history.png')