自学内容网 自学内容网

一个超级简单的清晰的LSTM模型的例子

废话不多说,把代码贴上去,就可以运行。然后看注释,自己慢慢品,细细品。

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


# 1. 生成时间序列数据,这里使用正弦函数模拟
def generate_time_series():
    time_steps = np.linspace(0, 10 * np.pi, 500, dtype=np.float32)
    data = np.sin(time_steps)
    data = np.expand_dims(data, axis=-1)
    return data


# 2. 划分训练集和测试集
def prepare_data(data):
    train_data = data[:400]
    test_data = data[400:]
    return train_data, test_data


# 3. 创建数据集
def create_dataset(data, time_steps):
    Xs, ys = [], []
    for i in range(len(data) - time_steps):
        v = data[i:(i + time_steps)]
        Xs.append(v)
        ys.append(data[i + time_steps])
    return np.array(Xs), np.array(ys)


# 4. 定义 LSTM 模型
def build_model(input_shape):
    model = tf.keras.Sequential([
        tf.keras.layers.LSTM(units=50, return_sequences=True, input_shape=input_shape),
        tf.keras.layers.LSTM(units=50),
        tf.keras.layers.Dense(units=1)
    ])
    model.compile(optimizer='adam', loss='mse')
    return model


# 5. 训练模型
def train_model(model, X_train, y_train, epochs=20):
    history = model.fit(
        X_train, y_train,
        epochs=epochs,
        batch_size=32,
        validation_split=0.1,
        shuffle=False
    )
    return history


# 6. 预测和可视化结果
def predict_and_visualize(model, X_train, y_train, X_test, y_test):
    train_predict = model.predict(X_train)
    test_predict = model.predict(X_test)

    plt.figure(figsize=(10, 6))
    plt.plot(y_train, label='True Train')
    plt.plot(train_predict, label='Predicted Train')
    plt.plot(range(len(y_train), len(y_train) + len(y_test)), y_test, label='True Test')
    plt.plot(range(len(y_train), len(y_train) + len(y_test)), test_predict, label='Predicted Test')
    plt.legend(loc='upper left')
    plt.show()


def plot_loss(history):
    plt.plot(history.history['loss'], label='Training Loss')
    plt.plot(history.history['val_loss'], label='Validation Loss')
    plt.title('Model Loss')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend(loc='upper right')
    plt.show()


if __name__ == "__main__":
    # 生成数据
    data = generate_time_series()
    train_data, test_data = prepare_data(data)
    time_steps = 10
    X_train, y_train = create_dataset(train_data, time_steps)
    X_test, y_test = create_dataset(test_data, time_steps)

    # 构建模型
    input_shape = (X_train.shape[1], X_train.shape[2])
    model = build_model(input_shape)

    # 训练模型
    history = train_model(model, X_train, y_train, epochs=20)

    # 显示训练的loss,val_loss
    plot_loss(history)

    # 预测和可视化
    predict_and_visualize(model, X_train, y_train, X_test, y_test)

原文地址:https://blog.csdn.net/weixin_39766667/article/details/145192961

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!