-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode_of_thesis(2s_1sec_overlap)_10.py
148 lines (103 loc) · 4.63 KB
/
code_of_thesis(2s_1sec_overlap)_10.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
# -*- coding: utf-8 -*-
"""Code of Thesis(2s_1sec overlap)_10
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1b9zcvceyLBN2D6x_M7JUuLnR_Lvonbnr
"""
from tensorflow.python.client import device_lib
device_lib.list_local_devices()
import matplotlib.pyplot as plt
from sklearn import metrics
from keras import layers
from keras import models
import tensorflow as tf
from scipy import io
import numpy as np
import keras
import cv2
trs = training_sample_size=12000 #
tes = test_sample_size=1798 #
dataset = io.loadmat('/content/drive/MyDrive/uni project/2_Class/2sec(1sec_overlap)/D_2c_shuffle_normal_2s(1sec overlap).mat')
x_train_original = np.squeeze(dataset['data'][:trs])
x_test_original = np.squeeze(dataset['data'][trs:trs+tes])
y_train_original = np.squeeze(dataset['label'][:trs])
y_test_original = np.squeeze(dataset['label'][trs:trs+tes])
x_train_dsize = [cv2.resize(img, dsize=(4, 1024)) for img in x_train_original]
x_test_dsize = [cv2.resize(img, dsize= (4, 1024)) for img in x_test_original]
x_train_original_re = [x.reshape(1024*4) for x in x_train_dsize]
x_test_original_re = [x.reshape(1024*4) for x in x_test_dsize]
x_train = np.array(x_train_original_re)
x_test = np.array(x_test_original_re)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train = x_train.reshape(-1,1024,4,1)
x_test = x_test.reshape(-1,1024,4,1)
y_train = keras.utils.to_categorical(y_train_original, num_classes=2)
y_test = keras.utils.to_categorical(y_test_original, num_classes=2)
model = models.Sequential()
model.add(layers.Conv2D(8, kernel_size=(4, 4),activation='relu', padding='same',input_shape=(1024,4,1)))
model.add(layers.BatchNormalization())
model.add(layers.Conv2D(16, kernel_size=(3, 3),activation='relu', padding='same'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.BatchNormalization())
model.add(layers.Conv2D(32, kernel_size=(3, 3),activation='relu', padding='same'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.BatchNormalization())
model.add(layers.Dropout(0.5))
model.add(layers.Flatten())
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.ActivityRegularization(l1=0.003, l2=0.003))
model.add(layers.Dense(2, activation='softmax'))
model.summary()
dot_img_file = './drive/MyDrive/uni project/2sec(1sec_overlap)/model_CNN.png'
tf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True)
model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.0002),
loss=keras.losses.CategoricalCrossentropy(),
metrics=['accuracy'])
history = model.fit(x_train, y_train,epochs=400, batch_size=64, validation_split=0.15)
# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
test_loss, test_acc = model.evaluate(x_test, y_test)
test_labels_p_org = model.predict(x_test)
test_labels_p = np.argmax(test_labels_p_org, axis=1)
print()
print(test_labels_p)
print(y_test_original)
from sklearn import metrics
confusion_matrix = metrics.confusion_matrix(y_test_original, test_labels_p)
cm_display = metrics.ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = [False, True])
cm_display.plot()
plt.show()
model.save_weights('/content/drive/MyDrive/uni project/weight')
model.save('/content/drive/MyDrive/uni project/model.h5')
#(True Positive + True Negative) / Total Predictions
Accuracy = metrics.accuracy_score(y_test_original, test_labels_p)
#True Positive / (True Positive + False Positive)
Precision = metrics.precision_score(y_test_original, test_labels_p)
#True Positive / (True Positive + False Negative)
Sensitivity_recall = metrics.recall_score(y_test_original, test_labels_p)
#True Negative / (True Negative + False Positive)
Specificity = metrics.recall_score(y_test_original, test_labels_p, pos_label=0)
# 2 * ((Precision * Sensitivity) / (Precision + Sensitivity))
F1_score = metrics.f1_score(y_test_original, test_labels_p)
print({"Accuracy":Accuracy})
print({"Precision":Precision})
print({"Sensitivity_recall":Sensitivity_recall})
print({"Specificity":Specificity})
print({"F1_score":F1_score})