运用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。但是需要注意的是,金融市场具有波动性和不确定性,模型预测结果并不能完全准确地反映市场变动。为了提高预测精度,可以尝试加入智能优化算法(如模拟退火、遗传算法、粒子群优化等)对模型进行优化。
热门推荐
知识建构共同体:概念、要素与实践应用
建安七子巧记法 建安七子和竹林八贤;“建安七子”
闲敲棋子落灯花:文人墨客下的悠然生活与艺术审美
春晚看无锡,不止于舞台!
培养孩子阅读理解能力的基础小技巧,坚持做得高分
如何查询摩托车违章记录?这种记录对驾驶安全有何影响?
RSTP技术细节
苏打粉能美白牙齿吗?使用方法和注意事项全解析
辨别英语词性的方法
你头上的“旋儿”怎么转?竟然和南北半球有关!?
渲染优化策略,如何在有限资源下实现最佳视觉效果
2025年国家电网考试全流程解析,从网申到入职的五大关键步骤!
从20多万元降到5万元 人工耳蜗将大幅降价
对方是喜欢你还是“利用你”,一目了然
热刺计划续约本坦库尔:乌拉圭中场强力助阵续写辉煌
新书|AI之后量子计算成科技领域新热点,量子计算机将如何改变我们的世界?
家装碳晶板的使用寿命及安装方法详解
合肥8所一本大学排名及特色介绍
家里湿气太重用什么办法能解决
数学:一切学科的基础与学习的基石
人类是从什么时候开始穿上衣服的?
讲清楚了!配电箱一级、二级、三级是什么意思?
高新技术企业专利转让:助力创新与产业升级
超级超限是什么意思
2017-2027年日本总人口及预测数据分析
宝宝肺炎疫苗选对了吗,13价还是23价?
探索“侘寂”的含义——日本美学的独特概念
招聘流程透明化:提升候选人体验的关键
流量卡怎么查询剩余流量?一分钟教你快速学会
25个关于动物的有趣冷知识,你知道几个?