-
Notifications
You must be signed in to change notification settings - Fork 0
/
2class_lstm_padded.py
158 lines (126 loc) · 5.83 KB
/
2class_lstm_padded.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
# -*- coding: utf-8 -*-
"""2class_LSTM_padded.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1L0smHQgO4U-Wzzi1piUCeF3zWWiPQgwX
"""
'''This code gives the neural network model for classification of multi-particle events using padded LSTM approach having both 2-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
'''Data sets are availiable on git-hub page. But i have used google drive to access the datasets'''
from google.colab import drive
drive.mount('/content/drive')
with open("drive/My Drive/Difr/Difr00.txt") as new_sig:
new_signal = [line.split() for line in new_sig]
with open("drive/My Drive/MinBias/MinBias00.txt") as new_backg:
new_background = [line.split() for line in new_backg]
new_sig_arr = np.array(new_signal)
new_back_arr = np.array(new_background)
for i in range(len(new_sig_arr)):
for j in range(len(new_sig_arr[i])):
new_sig_arr[i][j] = float(new_sig_arr[i][j])
for i in range(len(new_back_arr)):
for j in range(len(new_back_arr[i])):
new_back_arr[i][j] = float(new_back_arr[i][j])
new_signal_pythia_class = []
new_background_pythia_class = []
for i in range(new_sig_arr.shape[0]):
new_signal_pythia_class.append(1) #1--> Signal, 0--> Background
new_background_pythia_class.append(0)
new_sig_pythia_class = np.array(new_signal_pythia_class)
new_back_pythia_class = np.array(new_background_pythia_class)
new_Stacked_data_pythia = np.concatenate((new_sig_arr,new_back_arr))
# stacking the Signal and BAckground events for classification
new_Stacked_class_pythia = np.concatenate((new_sig_pythia_class,new_back_pythia_class))
from sklearn.utils import shuffle #shuffling the data
new_Data_org_pythia, new_Class_org_pythia = shuffle(new_Stacked_data_pythia, new_Stacked_class_pythia)
new_pad_data_pythia = pad_sequences(new_Data_org_pythia, padding='post')
print(new_pad_data_pythia.shape)
'''Model Starts Here'''
X_train, X_test, y_train, y_test = train_test_split( new_pad_data_pythia[0:80000], new_Class_org_pythia[0:80000], test_size=0.3, random_state=42) #Train-test spliting
X_val = X_test[12000:24000]
y_val = y_test[12000:24000]
X_test = X_test[0:12000]
y_test = y_test[0:12000]
y_train = np_utils.to_categorical(y_train, 2)
y_test = np_utils.to_categorical(y_test, 2) #Conversion of 1 and 0 to binary units for categorical cross entropy
y_val = np_utils.to_categorical(y_val, 2)
X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))
X_test = np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
X_val = np.reshape(X_val,(X_val.shape[0],X_val.shape[1],1))
# Model variables
batch_size = 100
epochs = 5
# Used datasets
data_train = X_train
data_test = X_test
data_val = X_val
class_train = y_train
class_test = y_test
class_val = y_val
def base_model():
model = Sequential()
model.add(Masking(mask_value=0, input_shape=(None,1)))
model.add(LSTM(35,input_shape=(None,1),return_sequences=False))
model.add(Dropout(rate = 0.3))
model.add(Dense(2, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[metrics.categorical_accuracy])
return model
event_cf = base_model()
event_cf.summary()
#sequential_model_to_ascii_printout(event_cf)
plot_model(event_cf)
es = EarlyStopping(monitor='val_categorical_accuracy', mode='max', verbose=1, patience=10)
mc = ModelCheckpoint('best_model_lstm_mask.h5', monitor='val_categorical_accuracy', mode='max', verbose=1, save_best_only=True)
event_cf = event_cf.fit(data_train, class_train, batch_size=batch_size, epochs=epochs, validation_data=(data_val,class_val),shuffle=True, callbacks=[es, mc])
saved_model = load_model('best_model_lstm_mask.h5')
# evaluate loaded model
scores_train = saved_model.evaluate(data_train, class_train, verbose=0)
scores_test = saved_model.evaluate(data_test, class_test, verbose=0)
scores_val = saved_model.evaluate(data_val, class_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(data_test, verbose=2)
yy_pred = np.argmax(YY_pred, axis=1)
yy_test2 = np.argmax(class_test, axis=1)
#confusion matrix
cm = confusion_matrix(np.argmax(class_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(2),
range(2))
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()