LSTM(长短时记忆网络)是处理时间序列数据的强大工具,常用于股票预测、天气分析等场景。以下是一个完整的实践指南:
🛠️ 环境准备
- 安装 TensorFlow:
pip install tensorflow
- 导入必要库:
import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense
📊 数据预处理
- 加载数据(以股票数据为例):
data = pd.read_csv('/path/to/your/data.csv')
- 归一化处理:
from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0,1)) scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1,1))
- 构建训练集与测试集:
train_data = scaled_data[:int(len(scaled_data)*0.8)] test_data = scaled_data[int(len(scaled_data)*0.8):]
🧱 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(units=50))
model.add(Dense(units=1)) # 输出层
🚀 训练与预测
- 编译模型:
model.compile(optimizer='adam', loss='mean_squared_error')
- 训练:
model.fit(x_train, y_train, epochs=25)
- 预测:
predictions = model.predict(x_test)
📈 结果可视化
将预测值还原并绘制对比图:
predicted_prices = scaler.inverse_transform(predictions)
plt.plot(predicted_prices, color='red', label='Predicted Price')
plt.plot(actual_prices, color='blue', label='Actual Price')
plt.legend()
📚 扩展阅读
想深入学习LSTM进阶技巧?点击此处查看系列教程 获取更多实战案例!