深度学习 交易预测 LSTM 层的神经元数量、训练轮数

以下是一个使用 Python 和 Keras 库构建 LSTM 模型进行交易预测的代码示例,同时会展示如何调整 LSTM 层的神经元数量和训练轮数,代码中还包含了不同参数下的实验对比,帮助你理解它们对模型性能的影响。

示例代码

import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt

# 数据加载与预处理
def load_and_preprocess_data(file_path):
    data = pd.read_csv(file_path)
    close_prices = data['Close'].values.reshape(-1, 1)
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_close_prices = scaler.fit_transform(close_prices)
    return scaled_close_prices, scaler

# 创建时间序列数据
def create_sequences(data, seq_length):
    xs, ys = [], []
    for i in range(len(data) - seq_length):
        x = data[i:i+seq_length]
        y = data[i+seq_length]
        xs.append(x)
        ys.append(y)
    return np.array(xs), np.array(ys)

# 构建 LSTM 模型
def build_lstm_model(seq_length, neurons):
    model = Sequential()
    model.add(LSTM(neurons, return_sequences=True, input_shape=(seq_length, 1)))
    model.add(LSTM(neurons, return_sequences=False))
    model.add(Dense(25))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mean_squared_error')
    return model

# 训练和评估模型
def train_and_evaluate_model(X_train, y_train, X_test, y_test, scaler, neurons, epochs):
    model = build_lstm_model(X_train.shape[1], neurons)
    model.fit(X_train, y_train, batch_size=32, epochs=epochs, verbose=0)
    predictions = model.predict(X_test)
    predictions = scaler.inverse_transform(predictions)
    y_test = scaler.inverse_transform(y_test)
    mse = mean_squared_error(y_test, predictions)
    return mse, predictions

# 主函数
def main():
    file_path = 'your_stock_data.csv'
    scaled_close_prices, scaler = load_and_preprocess_data(file_path)

    train_size = int(len(scaled_close_prices) * 0.8)
    train_data = scaled_close_prices[:train_size]
    test_data = scaled_close_prices[train_size:]

    seq_length = 30
    X_train, y_train = create_sequences(train_data, seq_length)
    X_test, y_test = create_sequences(test_data, seq_length)

    # 不同神经元数量和训练轮数的实验
    neuron_options = [30, 50, 70]
    epoch_options = [30, 50, 70]

    results = []
    for neurons in neuron_options:
        for epochs in epoch_options:
            mse, predictions = train_and_evaluate_model(X_train, y_train, X_test, y_test, scaler, neurons, epochs)
            results.append((neurons, epochs, mse))
            print(f'Neurons: {neurons}, Epochs: {epochs}, MSE: {mse}')

    # 可视化结果
    best_result = min(results, key=lambda x: x[2])
    best_neurons, best_epochs, _ = best_result
    best_model_mse, best_predictions = train_and_evaluate_model(X_train, y_train, X_test, y_test, scaler, best_neurons, best_epochs)

    plt.plot(y_test, label='Actual Prices')
    plt.plot(best_predictions, label='Predicted Prices')
    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.title(f'Best Model: Neurons={best_neurons}, Epochs={best_epochs}, MSE={best_model_mse:.4f}')
    plt.legend()
    plt.show()

if __name__ == "__main__":
    main()

代码解释

  1. 数据加载与预处理
    • load_and_preprocess_data 函数用于读取 CSV 文件中的股票收盘价数据,并使用 MinMaxScaler 进行归一化处理。
  2. 创建时间序列数据
    • create_sequences 函数将数据转换为适合 LSTM 模型输入的时间序列格式。
  3. 构建 LSTM 模型
    • build_lstm_model 函数根据指定的序列长度和神经元数量构建 LSTM 模型,包含两个 LSTM 层和两个全连接层,并使用 adam 优化器和均方误差损失函数进行编译。
  4. 训练和评估模型
    • train_and_evaluate_model 函数使用指定的训练轮数训练模型,并在测试集上进行评估,返回均方误差(MSE)和预测结果。
  5. 主函数
    • main 函数中定义了不同的神经元数量和训练轮数选项,进行多次实验,并记录每次实验的 MSE。
    • 最后找出 MSE 最小的模型配置,绘制实际价格和预测价格的对比图。

注意事项

  • 请将 'your_stock_data.csv' 替换为你实际的股票数据文件路径。
  • 你可以根据需要调整 neuron_optionsepoch_options 中的参数值,进行更多不同组合的实验。
  • 实际应用中,还可以考虑使用更复杂的模型结构、添加更多特征或进行超参数调优,以提高预测性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小赖同学啊

感谢上帝的投喂

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值