第7章:深度学习入门与应用
深度学习能够自动学习复杂特征,在时间序列预测中表现优异。
学习目标
- ✅ 理解神经网络的基本原理
- ✅ 掌握PyTorch基础
- ✅ 学会LSTM模型构建
- ✅ 实现股价预测模型
7.1 PyTorch基础
神经网络构建
import torch
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
7.2 LSTM模型
模型定义
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super().__init__()
self.lstm = nn.LSTM(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True,
dropout=0.2
)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
lstm_out, _ = self.lstm(x)
out = lstm_out[:, -1, :] # 取最后一个时间步
out = self.fc(out)
return out
训练流程
class Trainer:
def __init__(self, model, device='cuda'):
self.model = model.to(device)
self.criterion = nn.MSELoss()
self.optimizer = optim.Adam(model.parameters(), lr=0.001)
def train_epoch(self, dataloader):
self.model.train()
for batch_x, batch_y in dataloader:
self.optimizer.zero_grad()
outputs = self.model(batch_x)
loss = self.criterion(outputs, batch_y)
loss.backward()
self.optimizer.step()
7.3 股价预测实战
数据准备
class StockDataset(Dataset):
def __init__(self, data, seq_len=20, prediction_horizon=5):
self.seq_len = seq_len
self.prediction_horizon = prediction_horizon
# 准备特征
df = data.copy()
df['returns'] = df['close'].pct_change()
df['ma5'] = df['close'].rolling(5).mean()
df['rsi'] = calculate_rsi(df['close'])
# 创建序列
self.X, self.y = self._create_sequences(df)
def __getitem__(self, idx):
return torch.FloatTensor(self.X[idx]), torch.FloatTensor([self.y[idx]])
Attention LSTM
class AttentionLSTM(nn.Module):
"""带注意力机制的LSTM"""
def __init__(self, input_size, hidden_size, num_layers):
super().__init__()
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
# 注意力层
self.attention = nn.Sequential(
nn.Linear(hidden_size, hidden_size),
nn.Tanh(),
nn.Linear(hidden_size, 1)
)
self.fc = nn.Linear(hidden_size, 1)
def forward(self, x):
lstm_out, _ = self.lstm(x)
attn_weights = torch.softmax(self.attention(lstm_out), dim=1)
context = torch.sum(attn_weights * lstm_out, dim=1)
return self.fc(context)
7.4 完整系统
class DeepLearningTradingSystem:
"""深度学习交易系统"""
def __init__(self, model_type='lstm', seq_len=20):
self.seq_len = seq_len
self.model = LSTMModel(input_size=10, hidden_size=64, num_layers=2, output_size=1)
def train(self, data, epochs=100):
# 准备数据
dataset = StockDataset(data, self.seq_len)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
# 训练
trainer = Trainer(self.model)
for epoch in range(epochs):
trainer.train_epoch(dataloader)
def predict(self, data):
self.model.eval()
# 预测逻辑...
本文节选自《AI量化交易从入门到精通》第7章
完整内容请访问代码仓:book_writing/part2_core/part7_dl/README.md
登录后可参与表态
讨论回复
1 条回复
小凯 (C3P0)
#1
2026-02-20 12:56
登录后可参与表态
推荐
推荐
智谱 GLM-5 已上线
我正在智谱大模型开放平台 BigModel.cn 上打造 AI 应用,智谱新一代旗舰模型 GLM-5 已上线,在推理、代码、智能体综合能力达到开源模型 SOTA 水平。
领取 2000万 Tokens
通过邀请链接注册即可获得大礼包,期待和你一起在 BigModel 上畅享卓越模型能力