运用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。但是需要注意的是,金融市场具有波动性和不确定性,模型预测结果并不能完全准确地反映市场变动。为了提高预测精度,可以尝试加入智能优化算法(如模拟退火、遗传算法、粒子群优化等)对模型进行优化。
热门推荐
WiFi连接问题终结者:NETworkManager使用指南
双十一剁手党必看:WiFi连接问题终极解决指南
WiFi连接问题?教你三步搞定硬件排查
普华永道:中国企业融合儒家思想创新管理,贡献全球智慧
严格执行操作规程,混料企业降本增效又保安全
PLC混料控制系统应用实践:某化工企业减员70%,合格率提升95%
PLC混料控制系统:实现精准控制与成本优化的利器
中欧建交50周年前夕,工商学院论坛聚焦跨文化领导力
临沂三大招牌美食:光棍鸡、煎饼、糁,必打卡!
沂蒙煎饼和临沂炒鸡,舌尖上的非遗美味
脑血管系统全解析:供应20%血液,守护大脑健康
提琴演奏必备:松香的正确挑选与使用方法
双十一电商平台特色蔬菜礼盒热卖,健康消费引领新趋势
海南旅游攻略:精选航班机票购买指南与旅行贴士
正确按压加冷热敷,轻松应对抽血后淤青
打针后淤青处理:24小时是关键
罗曼·利普斯基上海驻地,开发“上海算法”融合中西艺术
许嫣医生的育儿智慧:12个教养策略打造快乐高效的学习环境
2024中国航展:激光锡焊引领航空航天新纪元
激光焊机在新材料加工中的优势:以储能和消费电子行业为例
激光焊机助力新能源车发展
从饮食到运动:轻度二尖瓣关闭不全的全方位管理指南
二尖瓣关闭不全:药物手术双管齐下,及时治疗是关键
松香:一种重要天然树脂的化学成分与应用
跟着罗桑游西藏:15天深度探访藏地精华景点
2024财富中国商界女性榜:王来春居首,半数企业布局海外
董明珠苏州考察谈合作,格力在智能装备等领域持续突破
95后女孩掌舵5000元/晚奢华酒店,创新管理赢得行业认可
社保基金三季度持仓:112亿布局34股,有色金属持仓居首
三季度社保基金持仓揭秘:重仓神火股份,加仓有色金属