-
Notifications
You must be signed in to change notification settings - Fork 2
/
cnn_wave.py
155 lines (126 loc) · 5.05 KB
/
cnn_wave.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
# -*- coding: utf-8 -*-
"""
Created on Mon May 22 16:08:26 2017
@author: Amajid Sinar
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
#Import training set
training_set = pd.read_csv("training_set.csv", delimiter=";")
X_train = training_set.iloc[:,1:].values
y_train = training_set.iloc[:,0:1].values
#Import test set
test_set = pd.read_csv("test_set_v2.csv", delimiter=";")
X_test = test_set.iloc[:,1:].values
y_test = test_set.iloc[:,0:1].values
#Import test set
#test_set = pd.read_csv("test_set.csv", delimiter=";")
#X_test = test_set.iloc[:,1:].values
#y_test = test_set.iloc[:,0:1].values
#Scale the data
from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.fit_transform(X_test)
#Convert X into 3D tensor
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))
#Importing the CNN libraries
from keras.models import Sequential
from keras.layers import Conv1D,MaxPooling1D,Flatten
from keras.layers import Dropout,Dense
from keras.layers.normalization import BatchNormalization
#Initializing the CNN
classifier = Sequential()
#Convolution and MaxPooling
classifier.add(Conv1D(filters=4,kernel_size=4,activation='relu',input_shape=(X_train.shape[1],1)))
classifier.add(MaxPooling1D(strides=4))
classifier.add(BatchNormalization())
#Flatten
classifier.add(Flatten())
#Full Connection
classifier.add(Dropout(0.25))
classifier.add(Dense(8, activation='relu'))
classifier.add(Dropout(0.25))
classifier.add(Dense(1,activation='sigmoid'))
#Print summary
print(classifier.summary())
#Configure the learning process
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history=classifier.fit(X_train,y_train, batch_size=64, epochs=5, validation_data=(X_test,y_test))
print(history.history.keys())
# "Accuracy"
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# "Loss"
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
#---------------------------------------------------------------------------------
#Evaluating
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
def build_classifier():
classifier = Sequential()
classifier.add(Conv1D(filters=4,kernel_size=4,activation='relu',input_shape=(X_train.shape[1],1)))
classifier.add(MaxPooling1D(strides=4))
# classifier.add(BatchNormalization())
classifier.add(Flatten())
# classifier.add(Dropout(0.25))
classifier.add(Dense(8, activation='relu'))
# classifier.add(Dropout(0.25))
classifier.add(Dense(1,activation='sigmoid'))
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
return classifier
classifier = KerasClassifier(build_fn=build_classifier, batch_size = 32, epochs = 5)
accuracies = cross_val_score(classifier, X=X_train, y=y_train, cv=10)
mean = accuracies.mean()
variance = accuracies.std()
#---------------------------------------------------------------------------------
#Parameter tuning
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
def build_classifier(optimizer, hnode, dropout1=0, dropout2=0, filters, kernel_size,strides):
classifier = Sequential()
classifier.add(Conv1D(filters=filters,kernel_size=kernel_size,activation='relu',input_shape=(X_train.shape[1],1)))
classifier.add(MaxPooling1D(strides=strides))
#classifier.add(BatchNormalization())
classifier.add(Flatten())
classifier.add(Dropout(dropout1))
classifier.add(Dense(hnode, activation='relu'))
classifier.add(Dropout(dropout2))
classifier.add(Dense(1,activation='sigmoid'))
classifier.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
return classifier
classifier = KerasClassifier(build_fn=build_classifier)
parameters = {'batch_size': [25,32],
'epochs': [5,10],
'optimizer': ['adam', 'rmsprop'],
'dropout1' : [0.1,0.15,0.2,0.25],
'dropout2' : [0.1,0.15,0.2,0.25],
'hnode' : [6,7,8,9,10],
'filters': [2,3,4,5,6],
'kernel_size': [2,3,4,5,6],
'strides': [2,3,4,5,6]
}
grid_search = GridSearchCV(estimator=classifier,
param_grid = parameters,
scoring = 'accuracy',
cv = 10)
grid_search = grid_search.fit(X_train, y_train)
best_parameters = grid_search.best_params_
best_accuracy = grid_search.best_score_
#---------------------------------------------------------------------------------
performace = classifier.evaluate(X_test,y_test)
y_pred = classifier.predict_classes(X_test)