CNNetwork.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. import numpy as np
  2. from keras.callbacks import EarlyStopping
  3. from keras.models import Sequential
  4. from keras.layers import Dense, Conv1D, MaxPooling1D, Flatten
  5. from sklearn.metrics import confusion_matrix
  6. def build_cnn_network():
  7. model = Sequential()
  8. model.add(Conv1D(32, kernel_size=5, strides=1,
  9. activation='relu',
  10. input_shape=(122, 1)))
  11. model.add(MaxPooling1D(pool_size=2, strides=2))
  12. model.add(Conv1D(64, 5, activation='relu'))
  13. model.add(MaxPooling1D(pool_size=2))
  14. model.add(Flatten())
  15. model.add(Dense(1000, activation='relu'))
  16. model.add(Dense(5, activation='softmax'))
  17. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
  18. return model
  19. def run_cnn_network(train, target, epochs):
  20. cnn = build_cnn_network()
  21. train = np.expand_dims(train, axis=2)
  22. early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=3, verbose=0, mode='auto')
  23. cnn.fit(x=train, y=target, epochs=epochs, validation_split=0.1, batch_size=128, callbacks=[early_stopping])
  24. return cnn
  25. def evaluate_cnn_network(cnn, test, test_target, flag):
  26. loss, accuracy = cnn.evaluate(np.expand_dims(test, axis=2), test_target, batch_size=None, verbose=1)
  27. # print('[-]( 测试集: ' + flag + ' ) 测试损失为:' + str(loss) + ' 准确度为:' + str(accuracy))
  28. return loss, accuracy