引自免费微信小程序:皆我百晓生
为了构建一个使用多维度数据进行黄金价格预测的LSTM模型,首先确保已经安装了必要的库,包括TensorFlow、Keras、pandas等。如果你尚未安装,可以使用以下命令安装:
pip install tensorflow pandas numpy matplotlib sklearn
接下来,我们将按照以下步骤进行操作:
- 导入所需库
- 准备数据集
- 数据预处理
- 构建LSTM模型
- 训练模型
- 评估模型
- 使用模型进行预测
代码示例:
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
# 假设你已经有了一个包含多个特征(例如开盘价、收盘价、最高价、最低价)和目标变量(黄金价格)的数据框df
# df = ...
# 将数据转换为时间序列数据
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
look_back = 60 # 可视化选择的时间窗口长度,可以根据需求调整
train_size = int(len(df) * 0.8)
test_size = len(df) - train_size
train, test = df[0:train_size], df[train_size:len(df)]
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(train)
dataX, dataY = create_dataset(dataset, look_back)
x_train, x_test, y_train, y_test = train_test_split(dataX, dataY, test_size=0.2, shuffle=False)
x_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
x_test = np.reshape(x_test, (x_test.shape[0], 1, x_test.shape[1]))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(1, look_back)))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
# 编译模型
model.compile(optimizer=Adam(lr=0.001), loss='mean_squared_error')
# 训练模型
history = model.fit(x_train, y_train, epochs=100, batch_size=32, validation_data=(x_test, y_test), verbose=2)
# 绘制训练过程中的损失函数曲线
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.show()
# 预测未来价格
inputs = dataset[-look_back:].reshape((1, 1, look_back))
predicted_price = model.predict(inputs)[0][0]
# 反归一化预测结果
predicted_price = scaler.inverse_transform([[predicted_price]])
print("Predicted Price:", predicted_price[0])
# 如果需要可视化原始数据和预测结果
plt.figure(figsize=(12, 6))
plt.plot(scaler.inverse_transform(dataset), label='Actual Price')
plt.plot(range(train_size, train_size + len(test)), scaler.inverse_transform(test), label='Real Price', linestyle='--')
plt.plot(range(train_size, train_size + len(test)), predicted_price, label='Predicted Price', linestyle='-.')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Price')
plt.title('Gold Price Prediction with LSTM')
plt.show()
在这个例子中,我们首先导入所需的库,然后准备数据集,并将其转化为时间序列数据。接着,我们创建了一个LSTM模型,其中包括两个LSTM层和一个全连接层。模型采用Adam优化器和均方误差作为损失函数进行编译。
在训练过程中,我们将数据集分为训练集和测试集,然后使用训练集对模型进行训练,并记录训练和验证的损失值。训练完成后,我们可以绘制损失曲线以分析模型性能。
最后,我们使用模型对未来价格进行预测,并将预测结果反归一化以便于理解。同时,我们可以将实际价格、真实价格和预测价格绘制成图表,以便更好地观察模型的表现。
注意:这个示例中的代码是基于一个假设的数据框df,你需要根据实际情况替换为你的数据。此外,可能需要根据数据的具体情况调整模型结构(比如LSTM单元数量、Dropout比例)、训练参数(比如epoch数、batch大小)以及超参数。

