Skip to content

LSTM

LSTM(Long Short-Term Memory,长短期记忆网络)是一种改进的 RNN(循环神经网络),解决了普通 RNN 容易“遗忘旧信息”或“梯度消失”的问题

核心思想:

  • 用“记忆单元”保存长期趋势;
  • 用“门结构”控制哪些信息该保留、哪些该遗忘;
  • 学习历史股价中的规律,从而预测未来走势。

torch的库

https://docs.pytorch.org/docs/stable/generated/torch.nn.LSTM.html

torch有现成的LSTM函数

在PyTorch中,一个标准的LSTM层是这样定义的:

torch.nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)

参数解释:

  • input_size: 每一天输入特征的维度(如:开盘价、收盘价、成交量等)
  • hidden_size: LSTM隐藏层神经元数量(模型记忆容量)
  • num_layers: 堆叠的LSTM层数(越多→更复杂)
  • batch_first=True: 输入数据形状为 (batch_size, seq_len, input_size)

输入输出形状示意

以“用过去30天的收盘价预测第31天价格”为例:

  • 输入 X: [batch_size, 30, 1]
  • 输出 y: [batch_size, 1]

如果你加上成交量、最高价、最低价等特征,则变为 [batch_size, 30, feature_dim]

LSTM 层返回的内容

当你调用:

x = self.lstm(x)

PyTorch 的 nn.LSTM 实际上返回两个东西:

output, (hn, cn) = self.lstm(x)
  • output: 每个时间步的输出 → [batch_size, seq_len, hidden_size]
  • hn: 最后一个时间步的隐藏状态(hidden state) → [num_layers, batch_size, hidden_size]
  • cn: 最后一个时间步的细胞状态(cell state)

你只需要把 self.lstm(x) 的输出拆开,然后选取最后一个时间步的输出即可。

out = out[:, -1, :]  # 取最后一个时间步的输出

为什么不取全部时间步

其实在某些任务中我们确实会用全部时间步,比如:

  • 文本翻译(Seq2Seq)
  • 视频逐帧预测 但在“预测未来一个值”的任务中(股价、温度、销售额等), 我们只需要模型在最后时刻的状态(即对整个过去的理解)。

模型

当前我们只有价格1个特征,所以 input_size 是1,hidden_size 是记忆大小也是输出大小

class LSTM(nn.Module):

    def __init__(self):
        super(LSTM, self).__init__()
        self.lstm = nn.LSTM(input_size=1, hidden_size=30, num_layers=2, bias=True, batch_first=True)
        self.out = nn.Linear(30, 1)

    def forward(self, x):
        output, _ = self.lstm(x)
        return self.out(F.relu(output[:,-1,:]))

后面加入relu效果更好点

效果

image-20251006233533685