以下是一个使用 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 = 30X_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_resultbest_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()
代码解释
- 数据加载与预处理:
load_and_preprocess_data
函数用于读取 CSV 文件中的股票收盘价数据,并使用MinMaxScaler
进行归一化处理。
- 创建时间序列数据:
create_sequences
函数将数据转换为适合 LSTM 模型输入的时间序列格式。
- 构建 LSTM 模型:
build_lstm_model
函数根据指定的序列长度和神经元数量构建 LSTM 模型,包含两个 LSTM 层和两个全连接层,并使用adam
优化器和均方误差损失函数进行编译。
- 训练和评估模型:
train_and_evaluate_model
函数使用指定的训练轮数训练模型,并在测试集上进行评估,返回均方误差(MSE)和预测结果。
- 主函数:
main
函数中定义了不同的神经元数量和训练轮数选项,进行多次实验,并记录每次实验的 MSE。- 最后找出 MSE 最小的模型配置,绘制实际价格和预测价格的对比图。
注意事项
- 请将
'your_stock_data.csv'
替换为你实际的股票数据文件路径。 - 你可以根据需要调整
neuron_options
和epoch_options
中的参数值,进行更多不同组合的实验。 - 实际应用中,还可以考虑使用更复杂的模型结构、添加更多特征或进行超参数调优,以提高预测性能。