import numpy as np from keras.callbacks import EarlyStopping from keras.models import Sequential from keras.layers import Dense, Conv1D, MaxPooling1D, Flatten from sklearn.metrics import confusion_matrix def build_cnn_network(): model = Sequential() model.add(Conv1D(32, kernel_size=5, strides=1, activation='relu', input_shape=(122, 1))) model.add(MaxPooling1D(pool_size=2, strides=2)) model.add(Conv1D(64, 5, activation='relu')) model.add(MaxPooling1D(pool_size=2)) model.add(Flatten()) model.add(Dense(1000, activation='relu')) model.add(Dense(5, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model def run_cnn_network(train, target, epochs): cnn = build_cnn_network() train = np.expand_dims(train, axis=2) early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=3, verbose=0, mode='auto') cnn.fit(x=train, y=target, epochs=epochs, validation_split=0.1, batch_size=128, callbacks=[early_stopping]) return cnn def evaluate_cnn_network(cnn, test, test_target, flag): loss, accuracy = cnn.evaluate(np.expand_dims(test, axis=2), test_target, batch_size=None, verbose=1) # print('[-]( 测试集: ' + flag + ' ) 测试损失为:' + str(loss) + ' 准确度为:' + str(accuracy)) return loss, accuracy