赞
踩
import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout from keras.optimizers import Adam from sklearn.metrics import confusion_matrix # 创建模型 def create_model(input_shape): model = Sequential() model.add(LSTM(units=64, input_shape=input_shape, return_sequences=True)) model.add(Dropout(rate=0.2)) model.add(LSTM(units=32, return_sequences=True)) model.add(Dropout(rate=0.2)) model.add(LSTM(units=16, return_sequences=False)) model.add(Dense(units=1, activation='sigmoid')) optimizer = Adam(lr=0.001) model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) return model # 生成数据 x_train = np.random.rand(1000, 10, 5) # 1000个样本,10个时间步长,5个特征 y_train = np.random.randint(2, size=(1000, 1)) # 二分类标签 # 训练模型 model = create_model(input_shape=(10, 5)) history = model.fit(x_train, y_train, epochs=50, batch_size=32, validation_split=0.2) # 绘制损失函数图 plt.plot(history.history['loss'], label='train') plt.plot(history.history['val_loss'], label='validation') plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend() plt.show() # 预测测试集数据 x_test = np.random.rand(1000, 10, 5) # 100个测试数据,10个时间步长,5个特征 y_test = np.random.randint(2, size=(1000, 1)) # 二分类标签 #y_pred = model.predict_classes(x_test) y_pred = model.predict(x_test) # 计算混淆矩阵 cm = confusion_matrix(y_test, y_pred.argmax(axis=1)) print('Confusion Matrix') print(cm)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。