-
Notifications
You must be signed in to change notification settings - Fork 0
/
3class_cnn.py
182 lines (145 loc) · 6.72 KB
/
3class_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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# -*- coding: utf-8 -*-
"""3class_cnn
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1sATtE-seHtk1bJUEBzdHjI3VsObO3ENe
"""
'''This code gives the neural network model for classification of multi-particle events using Conventional Neural Network by using 2-D Binary maps of the padded vectors approach having both 3-class classification'''
import numpy as np
!pip install keras_sequential_ascii
import keras
import pandas as pd
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Reshape
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.layers import Dense , Flatten ,Embedding,Masking,Input, CuDNNLSTM
from keras.layers import Activation
from sklearn.preprocessing import MinMaxScaler
from keras import backend as K
from keras.layers import LSTM
from keras_sequential_ascii import sequential_model_to_ascii_printout
from keras.utils import plot_model
from keras.utils import np_utils
from keras.optimizers import SGD
from keras.constraints import maxnorm
from keras.callbacks import EarlyStopping
from keras.preprocessing.text import one_hot,Tokenizer
from keras.preprocessing.sequence import pad_sequences
from nltk import word_tokenize,sent_tokenize
from keras.callbacks import ModelCheckpoint
from keras.models import load_model
from keras import metrics
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import sys
from keras.models import Model
with open("drive/My Drive/DblDifr/DblDifr00.txt") as dbl_difr:
dbl_dif = [line.split() for line in dbl_difr]
with open("drive/My Drive/SinDifr/SinDifr00.txt") as sin_difr:
sin_dif = [line.split() for line in sin_difr]
with open("drive/My Drive/MinBias/MinBias00.txt") as bckg:
difr_bckg = [line.split() for line in bckg]
dbl_diff = np.array(dbl_dif)
sin_diff = np.array(sin_dif)
diff_bckg = np.array(difr_bckg)
for i in range(len(dbl_diff)):
for j in range(len(dbl_diff[i])):
dbl_diff[i][j] = float(dbl_diff[i][j])
for i in range(len(sin_diff)):
for j in range(len(sin_diff[i])):
sin_diff[i][j] = float(sin_diff[i][j])
for i in range(len(diff_bckg)):
for j in range(len(diff_bckg[i])):
diff_bckg[i][j] = float(diff_bckg[i][j])
dbl_diff_class = []
sin_diff_class = []
for i in range(dbl_diff.shape[0]):
dbl_diff_class.append(1)
sin_diff_class.append(0)
diff_bckg_class = []
for i in range(diff_bckg.shape[0]):
diff_bckg_class.append(2)
sin_dif_class = np.array(sin_diff_class)
dbl_dif_class = np.array(dbl_diff_class)
dif_bckg_class = np.array(diff_bckg_class)
diff_Stacked_data = np.concatenate((sin_diff,dbl_diff))
diff_Stacked_data = np.concatenate((diff_Stacked_data,diff_bckg))
# stacking the Signal and BAckground events for classification
diff_Stacked_class = np.concatenate((sin_diff_class,dbl_diff_class))
diff_Stacked_class = np.concatenate((diff_Stacked_class,diff_bckg_class))
from sklearn.utils import shuffle #shuffling the data
diff_Data_org, diff_Class_org = shuffle(diff_Stacked_data, diff_Stacked_class)
diff_pad_data = pad_sequences(diff_Data_org, padding='post')
print(diff_pad_data.shape)
diff_hist_train, diff_hist_test, diff_label_train, diff_label_test = train_test_split( diff_pad_data, diff_Class_org, test_size=0.3, random_state=42) #Train-test spliting
diff_hist_train.shape
diff_hist_val = diff_hist_test[15000:30000]
diff_label_val = diff_label_test[15000:30000]
diff_hist_test = diff_hist_test[0:15000]
diff_label_test = diff_label_test[0:15000]
import matplotlib.cm as cm
plt.title(diff_label_test[26])
plt.imshow(np.reshape(diff_hist_test[26],(9,15)), cmap=cm.binary)
plt.show()
diff_label_train = np_utils.to_categorical(diff_label_train, 3) #conversion of labels to binary notations
diff_label_test = np_utils.to_categorical(diff_label_test, 3)
diff_label_val = np_utils.to_categorical(diff_label_val, 3)
print(diff_label_test.shape)
img_rows =15
img_cols =9
img_size_flat = img_cols*img_rows
num_channels = 1
num_classes =3
diff_hist_train = np.reshape(diff_hist_train,(diff_hist_train.shape[0],1,img_rows,img_cols))
diff_hist_test = np.reshape(diff_hist_test,(diff_hist_test.shape[0],1,img_rows,img_cols))
diff_hist_val = np.reshape(diff_hist_test,(diff_hist_val.shape[0],1,img_rows,img_cols))
print(diff_hist_train.shape,diff_hist_test.shape,diff_hist_val.shape)
# Define Model
def base_model():
model = Sequential()
input_shape=(1,img_rows,img_cols)
model.add(Reshape((img_rows,img_cols,1),input_shape=input_shape))
model.add(Conv2D(80,kernel_size = 2,activation='relu',input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dropout(rate = 0.2))
model.add(Dense(32*img_rows,activation='relu',kernel_constraint=maxnorm(3))) #1024
model.add(Dropout(rate = 0.3))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[metrics.categorical_accuracy])
return model
diff_cnn_n = base_model()
diff_cnn_n.summary()
sequential_model_to_ascii_printout(diff_cnn_n)
plot_model(diff_cnn_n)
# patient early stopping
es = EarlyStopping(monitor='val_categorical_accuracy', mode='max', verbose=1, patience=10)
mc = ModelCheckpoint('best_model_diff_hist_conv2d.h5', monitor='val_categorical_accuracy', mode='max', verbose=1, save_best_only=True)
# fit model
diff_cnn = diff_cnn_n.fit(diff_hist_train, diff_label_train, batch_size=100, epochs=5, validation_data=(diff_hist_test,diff_label_test),shuffle=True, callbacks=[es, mc])
# load the saved model
saved_model = load_model('best_model_diff_hist_conv2d.h5')
# evaluate loaded model
scores_train = saved_model.evaluate(diff_hist_train, diff_label_train, verbose=0)
scores_test = saved_model.evaluate(diff_hist_test, diff_label_test, verbose=0)
scores_val = saved_model.evaluate(diff_hist_val, diff_label_val, verbose=0)
print("Accuracy Train: %.2f%% , Test: %.2f%% Val: %.2f%% " % (scores_train[1]*100, scores_test[1]*100, scores_val[1]*100)) #Efficiency(train and test)
# Confusion matrix result
from sklearn.metrics import classification_report, confusion_matrix
YY_pred = saved_model.predict(diff_hist_test, verbose=2)
yy_pred = np.argmax(YY_pred, axis=1)
yy_test2 = np.argmax(diff_label_test, axis=1)
#confusion matrix
cm = confusion_matrix(np.argmax(diff_label_test,axis=1),yy_pred) #Confusion matrix
print(cm)
# Visualizing of confusion matrix
import seaborn as sn
import pandas as pd
df_cm = pd.DataFrame(cm, range(3),
range(3))
plt.figure(figsize = (10,7))
sn.set(font_scale=1.4)#for label size
sn.heatmap(df_cm, annot=True,annot_kws={"size": 12})# font size
plt.show()