当前位置:   article > 正文

LSTM二分类预测Python代码,并输出模型训练的损失函数图_python resnet+lstm数据分类

python resnet+lstm数据分类
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)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/978243
推荐阅读
相关标签
  

闽ICP备14008679号