-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain2.py
157 lines (122 loc) · 5.88 KB
/
main2.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
from keras.layers import Dense, Conv1D, BatchNormalization, MaxPooling1D, Activation, Flatten
from keras.models import Sequential
from keras.utils import plot_model
from keras.regularizers import l2
import preprocess
from keras.callbacks import TensorBoard
import numpy as np
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import itertools
def plot_confusion_matrix(cm,
target_names,
title='Confusion matrix',
cmap=plt.cm.Greens, # 这个地方设置混淆矩阵的颜色主题,这个主题看着就干净~
normalize=True):
accuracy = np.trace(cm) / float(np.sum(cm))
misclass = 1 - accuracy
if cmap is None:
cmap = plt.get_cmap('Blues')
plt.figure(figsize=(15, 12))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
if target_names is not None:
tick_marks = np.arange(len(target_names))
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if normalize:
plt.text(j, i, "{:0.4f}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
else:
plt.text(j, i, "{:,}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
# 这里这个savefig是保存图片,如果想把图存在什么地方就改一下下面的路径,然后dpi设一下分辨率即可。
# plt.savefig('/content/drive/My Drive/Colab Notebooks/confusionmatrix32.png',dpi=350)
plt.show()
# 显示混淆矩阵
def plot_confuse(model, x_val, y_val, labels):
predictions = model.predict_classes(x_val, batch_size=batch_size)
truelabel = y_val.argmax(axis=-1) # 将one-hot转化为label
conf_mat = confusion_matrix(y_true=truelabel, y_pred=predictions)
# plt.figure()
plot_confusion_matrix(conf_mat, normalize=False, target_names=labels, title='Confusion Matrix')
def cm_plot(y, yp):
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y, yp) # 混淆矩阵
import matplotlib.pyplot as plt
plt.matshow(cm, cmap=plt.cm.Greens)
plt.colorbar()
for x in range(len(cm)):
for y in range(len(cm)):
plt.annotate(cm[x, y], xy=(x, y), horizontalalignment='center', verticalalignment='center')
# plt.subplots(figsize=(9, 9))
plt.ylabel('True label')
plt.xlabel('Predicted label')
return plt
# 训练参数
batch_size = 128
epochs = 12
num_classes = 10
length = 2048
BatchNorm = True # 是否批量归一化
number = 1000 # 每类样本的数量
normal = True # 是否标准化
rate = [0.6, 0.2, 0.2] # 测试集验证集划分比例
path = r'data\0HP'
x_train, y_train, x_valid, y_valid, x_test, y_test = preprocess.prepro(d_path=path, length=length,
number=number,
normal=normal,
rate=rate,
enc=True, enc_step=28)
x_train, x_valid, x_test = x_train[:, :, np.newaxis], x_valid[:, :, np.newaxis], x_test[:, :, np.newaxis]
# 输入数据的维度
input_shape = x_train.shape[1:]
print('训练样本维度:', x_train.shape)
print(x_train.shape[0], '训练样本个数')
print('验证样本的维度', x_valid.shape)
print(x_valid.shape[0], '验证样本个数')
print('测试样本的维度', x_test.shape)
print(x_test.shape[0], '测试样本个数')
model_name = "cnn_1D"
model = Sequential()
# 第一层卷积
model.add(
Conv1D(filters=16, kernel_size=7, strides=7, padding='same', kernel_regularizer=l2(1e-4), input_shape=input_shape))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling1D(pool_size=4, strides=4, padding='valid'))
# 从卷积到全连接需要展平
model.add(Flatten())
# 添加全连接层,共100个单元,激活函数为ReLU
model.add(Dense(units=100, activation='relu', kernel_regularizer=l2(1e-4)))
model.add(Dense(units=num_classes, activation='softmax', kernel_regularizer=l2(1e-4)))
# 编译模型
model.compile(optimizer='Adam', loss='categorical_crossentropy',
metrics=['accuracy'])
# TensorBoard调用查看一下训练情况
tb_cb = TensorBoard(log_dir='logs\{}'.format(model_name))
# 开始模型训练
model.fit(x=x_train, y=y_train, batch_size=batch_size, epochs=epochs,
verbose=1, validation_data=(x_valid, y_valid), shuffle=True,
callbacks=[tb_cb])
# 评估模型
score = model.evaluate(x=x_test, y=y_test, verbose=0)
print("测试集上的损失率:", score[0])
print("测试集上的准确率:", score[1])
plot_model(model=model, to_file='cnn-1D.png', show_shapes=True)
# =========================================================================================
# 最后调用这个函数即可。 test_x是测试数据,test_y是测试标签(这里用的是One——hot向量)
# labels是一个列表,存储了你的各个类别的名字,最后会显示在横纵轴上。
# 比如这里我的labels列表
labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9','10']
plot_confuse(model, x_test, y_test,labels)