运用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。但是需要注意的是,金融市场具有波动性和不确定性,模型预测结果并不能完全准确地反映市场变动。为了提高预测精度,可以尝试加入智能优化算法(如模拟退火、遗传算法、粒子群优化等)对模型进行优化。
热门推荐
儿童房怎样布置才能好看、实用、又显大?不做榻榻米,“成长型”原则才适用!
上饶师范学院不是985不是211,被教育部评为公办本科院校
n网mod下载慢:原因分析与提速策略
上饶师范学院2025年招生简章(含招生计划、录取分数线)
春秋战国时期赵国历代国君
大便总是黏腻、不成形?或是这3种原因导致,应及时调理或就医
喇叭音腔设计:【图文讲解】
新春走基层丨整理收纳师:房屋空间的“魔法师”
冬季总是“被电到”?轻松几招帮你远离静电!
八级工伤都有哪些赔偿
高三冲刺学习方法及技巧:如何高效学习
冰箱制冷系统故障检测全攻略
SATA固态硬盘如何查看健康程度?全面指南与实用工具推荐
动脉硬化来临前的6个信号,什么情况下需要进行动脉硬化检测
日本签证年收入没有10w怎么办
豪门足球俱乐部的精英训练营:技术提升与团队发展的关键
李世民的后宫佳丽
15种升高血红蛋白的最佳食物:预防贫血,增强健康
如何关闭Windows 10系统中软件的消息通知
路由器WiFi 2.4GHz和5GHz双频合一还是分开好?
中国十大情侣旅游胜地 中国十大适合情侣旅游的城市 国内情侣约会热门目的地推荐
员工职业发展的重要性与提升策略
人际交往怎样保护自己
如何正确擦拭液晶电视屏幕以保持其清晰度和延长使用寿命?
从科举制度看明朝兴盛原因,明朝科举制度变革之始末经过
墙面翻新需要铲掉旧漆吗
IP地址的格式类型详解:IPv4与IPv6的区别与特点
算命案件最新进展:法律视角下的责任与启示
免费免预约!北京5个能待一整天的室内场馆!
WLK冰冠城堡传说中的橙斧影之哀伤任务详解