运用LSTM预测黄金和比特币价格
创作时间:
作者:
@小白创作中心
运用LSTM预测黄金和比特币价格
引用
CSDN
1.
https://blog.csdn.net/2301_77294529/article/details/137124002
LSTM(长短期记忆)模型是一种特殊的循环神经网络(RNN),通过引入门机制解决了传统RNN的长记忆性问题。本文将介绍如何使用LSTM模型对黄金和比特币的价格进行预测,包括数据预处理、模型构建和结果可视化等步骤。
LSTM模型简介
LSTM模型通过引入三个门机制(遗忘门、更新门和输出门)来保护和控制细胞状态。门机制通过sigmoid函数和点乘操作实现,sigmoid函数的取值范围为0到1,决定了信息的传递量。当sigmoid取0时表示舍弃信息,取1时表示完全传输。
数据准备
本文使用2022年美赛C题提供的黄金和比特币数据。为了简化计算,将观察跨度设置为2,即根据前2天的数据预测下一天的价格。数据预处理步骤包括数据标准化和数据集划分。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
filepath = 'E:\desktop\chain1.csv'
data = pd.read_csv(filepath)
data = data.sort_values('Date')
print(data.head())
print(data.shape)
price = data[['Value']]
print(price.info())
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(-1, 1))
price['Value'] = scaler.fit_transform(price['Value'].values.reshape(-1, 1))
print(price['Value'].shape)
def split_data(stock, lookback):
data_raw = stock.to_numpy()
data = []
for index in range(len(data_raw) - lookback):
data.append(data_raw[index: index + lookback])
data = np.array(data);
test_set_size = data.shape[0]
train_set_size = data.shape[0]
x_train = data[:train_set_size, :-1, :]
y_train = data[:train_set_size, -1, :]
x_test = data[:train_set_size, :-1, :]
y_test = data[:train_set_size, -1, :]
return [x_train, y_train, x_test, y_test]
lookback = 2
x_train, y_train, x_test, y_test = split_data(price, lookback)
print('x_train.shape = ', x_train.shape)
print('y_train.shape = ', y_train.shape)
print('x_test.shape = ', x_test.shape)
print('y_test.shape = ', y_test.shape)
模型构建与训练
使用PyTorch构建LSTM模型,设置输入维度为1(只有Value),隐藏层特征维度为32,循环层数为2,预测维度为1。使用均方误差损失函数和Adam优化器进行模型训练。
import torch
import torch.nn as nn
x_train = torch.from_numpy(x_train).type(torch.Tensor)
x_test = torch.from_numpy(x_test).type(torch.Tensor)
y_train_lstm = torch.from_numpy(y_train).type(torch.Tensor)
y_test_lstm = torch.from_numpy(y_test).type(torch.Tensor)
y_train_gru = torch.from_numpy(y_train).type(torch.Tensor)
y_test_gru = torch.from_numpy(y_test).type(torch.Tensor)
input_dim = 1
hidden_dim = 32
num_layers = 2
output_dim = 1
num_epochs = 100
class LSTM(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers, output_dim):
super(LSTM, self).__init__()
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()
out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))
out = self.fc(out[:, -1, :])
return out
model = LSTM(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output_dim, num_layers=num_layers)
criterion = torch.nn.MSELoss()
optimiser = torch.optim.Adam(model.parameters(), lr=0.01)
hist = np.zeros(num_epochs)
start_time = time.time()
lstm = []
for t in range(num_epochs):
y_train_pred = model(x_train)
loss = criterion(y_train_pred, y_train_lstm)
print("Epoch ", t, "MSE: ", loss.item())
hist[t] = loss.item()
optimiser.zero_grad()
loss.backward()
optimiser.step()
training_time = time.time() - start_time
print("Training time: {}".format(training_time))
结果可视化
使用Seaborn库对预测结果和损失函数进行可视化。从图中可以看出,比特币和黄金的预测值拟合效果良好,损失函数值均低于0.5。
predict = pd.DataFrame(scaler.inverse_transform(y_train_pred.detach().numpy()))
original = pd.DataFrame(scaler.inverse_transform(y_train_lstm.detach().numpy()))
import seaborn as sns
sns.set_style("darkgrid")
fig = plt.figure()
fig.subplots_adjust(hspace=0.2, wspace=0.2)
plt.subplot(1, 2, 1)
ax = sns.lineplot(x=original.index, y=original[0], label="Data", color='royalblue')
ax = sns.lineplot(x=predict.index, y=predict[0], label="Training Prediction (LSTM)", color='tomato')
ax.set_title('Stock price', size=14, fontweight='bold')
ax.set_xlabel("Days", size=14)
ax.set_ylabel("Cost (USD)", size=14)
ax.set_xticklabels('', size=10)
plt.subplot(1, 2, 2)
ax = sns.lineplot(data=hist, color='royalblue')
ax.set_xlabel("Epoch", size=14)
ax.set_ylabel("Loss", size=14)
ax.set_title("Training Loss", size=14, fontweight='bold')
fig.set_figheight(6)
fig.set_figwidth(16)
plt.show()
结果分析
从预测结果来看,LSTM模型对黄金和比特币价格的预测效果良好,损失函数值均低于0.5。但是需要注意的是,金融市场具有波动性和不确定性,模型预测结果并不能完全准确地反映市场变动。为了提高预测精度,可以尝试加入智能优化算法(如模拟退火、遗传算法、粒子群优化等)对模型进行优化。
热门推荐
芦笋外面的皮怎么处理
短剧全集《长生渡,我修仙多年强亿点怎么了》情感探索之旅
咳嗽有痰吃阿奇霉素还是阿莫西林
梅涅劳斯定理教学(梅涅劳斯定理)
个人隐私泄露风险及应对策略
专利申请“减速竞质”,国货美妆研发步入体系化PK
如何诊断多重人格?
双重人格怎么治疗
孕妇睡眠优化秘籍:提高睡眠质量的方法分享
全省唯一!新安樱桃入选中国全球重要农业文化遗产预备名单
天热容易出汗怎么回事
华法林剂量怎么调整?3表汇总!
爱屋及乌的下一句及出处
猫在家里找不到了怎么办?
汽车脚垫材质选购指南:从克林毯到丝圈,哪种最适合你?
「高尔夫推杆技巧」受用终生的推杆基本要素和练习方法
线性代数导引:仿射空间
什么是布鲁斯音乐
惊喜!20万内竟能买这些豪车?8款性价比车型推荐,你选哪款?
A股并购重组潮持续升温,这些公司最新动态曝光
龙头斩获5天3板 本周披露并购重组进展的A股名单一览
宝宝湿疹红屁屁护理,抚触油与护臀膏效果对比
二审提出新证据的规定是什么
“中国电影很精彩” 中国传统文化独特魅力海外收获认可
用了半年的菜板,居然这么脏,许多人都不知道正确的清洗方法
八字命理:天生与佛道有缘的特征解析
智能摄像头使用指南:解除绑定、恢复出厂设置与存储卡格式化
打工人群体的健康守护者:量身打造的运动指南
印度人口已超14.5亿,为何还鼓励生育?
透析总数突破百万人!我国最新透析详细数据发布