# 深度学习一点通：PyTorch Transformer 预测股票价格，虚拟数据，chatGPT同源模型

``````import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
``````

## 产生训练模型的数据

``````num_days = 200
stock_prices = np.random.rand(num_days) * 100
``````

## 预处理数据

``````input_seq_len = 10
output_seq_len = 5
num_samples = num_days - input_seq_len - output_seq_len + 1

src_data = torch.tensor([stock_prices[i:i+input_seq_len] for i in range(num_samples)]).unsqueeze(-1).float()
tgt_data = torch.tensor([stock_prices[i+input_seq_len:i+input_seq_len+output_seq_len] for i in range(num_samples)]).unsqueeze(-1).float()
``````

## 创建自定义转换器模型

``````class StockPriceTransformer(nn.Module):
def __init__(self, d_model, nhead, num_layers, dropout):
super(StockPriceTransformer, self).__init__()
self.input_linear = nn.Linear(1, d_model)
self.transformer = nn.Transformer(d_model, nhead, num_layers, dropout=dropout)
self.output_linear = nn.Linear(d_model, 1)

def forward(self, src, tgt):
src = self.input_linear(src)
tgt = self.input_linear(tgt)
output = self.transformer(src, tgt)
output = self.output_linear(output)
return output

d_model = 64
num_layers = 2
dropout = 0.1

model = StockPriceTransformer(d_model, nhead, num_layers, dropout=dropout)
``````

## 训练模型

``````epochs = 100
lr = 0.001
batch_size = 16

criterion = nn.MSELoss()
``````

``````for epoch in range(epochs):
for i in range(0, num_samples, batch_size):
src_batch = src_data[i:i+batch_size].transpose(0, 1)
tgt_batch = tgt_data[i:i+batch_size].transpose(0, 1)

output = model(src_batch, tgt_batch[:-1])
loss = criterion(output, tgt_batch[1:])
loss.backward()
optimizer.step()

print(f"Epoch {epoch+1}/{epochs}, Loss: {loss.item()}")
``````

## 预测未来 5 天的股票价格

``````src = torch.tensor(stock_prices[-input_seq_len:]).unsqueeze(-1).unsqueeze(1).float()
tgt = torch.zeros(output_seq_len, 1, 1)

for i in range(output_seq_len):
prediction = model(src, tgt[:i+1])
tgt[i] = prediction[-1]

output = tgt.squeeze().tolist()
print("Next 5 days of stock prices:", output)
``````

## AI好书推荐

AI日新月异，但是万丈高楼拔地起，离不开良好的基础。您是否有兴趣了解人工智能的原理和实践？ 不要再观望！ 我们关于 AI 原则和实践的书是任何想要深入了解 AI 世界的人的完美资源。 由该领域的领先专家撰写，这本综合指南涵盖了从机器学习的基础知识到构建智能系统的高级技术的所有内容。 无论您是初学者还是经验丰富的 AI 从业者，本书都能满足您的需求。 那为什么还要等呢？

THE END