Pytorch中nn.LSTM与nn.LSTMCell

本文介绍了Pytorch中的LSTM和LSTMCell类,包括它们的计算过程、参数说明以及输入输出格式。LSTM用于处理序列数据,而LSTMCell是其基本单元,适用于手动管理每个时间步的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class torch.nn.LSTM(*args, **kwargs)

在这里插入图片描述

对输入序列的每个元素,LSTM的每层都会执行以下计算:
在这里插入图片描述

h t h_t ht是时刻 t t t的隐状态, c t c_t ct是时刻 t t t的细胞状态, x t x_t xt是上一层的在时刻 t t t的隐状态或者是第一层在时刻 t t t的输入。 i t , f t , g t , o t i_t, f_t, g_t, o_t it,ft,gt,ot 分别代表 输入门,遗忘门,细胞和输出门。

参数说明:

  • input_size – 输入的特征维度,(特征向量的长度,如2048)
    hidden_size – 隐状态的特征维度,(每个LSTM单元或者时间步的输出的ht的维度,单元内部有权重与偏差计算)
    num_layers – 层数(和时序展开要区分开), RNN层的个数(在竖直方向堆叠的多个相同个数单元的层数)
    bias – 如果为False,那么LSTM将不会使用 b i h , b h h b_{ih},b_{hh} bih,
### 调整 PyTorch 中 `nn.LSTM` 的输出维度 在 PyTorch 中,`nn.LSTM` 默认返回的输出形状为 `[seq_len, batch_size, hidden_size * num_directions]`[^3]。如果希望将其调整为目标形状 `[B, seq_len, d_model]`,可以通过以下方式实现: #### 输出维度转换逻辑 1. **默认输出形状** LSTM 的默认输出形状为 `(seq_len, batch_size, hidden_size)` 或者对于双向 LSTM 则为 `(seq_len, batch_size, 2*hidden_size)`。 2. **目标形状分析** 假设目标形状为 `[batch_size, seq_len, d_model]`,其中: - `batch_size (B)` 是批量大小, - `seq_len` 是序列长度, - `d_model` 可能等于隐藏层大小 (`hidden_size`) 或其他特定尺寸。 3. **转置操作** 使用 `.permute()` 函数可以重新排列张量的维度顺序。例如,将 `(seq_len, batch_size, hidden_size)` 转换为 `(batch_size, seq_len, hidden_size)`[^4]。 4. **线性变换(可选)** 如果需要进一步修改最后一维的大小(即从 `hidden_size` 转变为 `d_model`),可以在 LSTM 后接一个全连接层(`nn.Linear`)。这允许自定义最终输出的最后一维大小[^1]。 #### 实现方法 以下是完整的代码示例,展示如何通过上述步骤调整输出维度: ```python import torch import torch.nn as nn class CustomLSTM(nn.Module): def __init__(self, input_size, hidden_size, output_dim, num_layers=1, bidirectional=False): super(CustomLSTM, self).__init__() self.lstm = nn.LSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=False, # 默认为 False,保持输入形状为 (seq_len, batch, input_size) bidirectional=bidirectional ) direction_factor = 2 if bidirectional else 1 self.fc = nn.Linear(hidden_size * direction_factor, output_dim) def forward(self, x): lstm_out, _ = self.lstm(x) # lstm_out shape: (seq_len, batch_size, hidden_size * num_directions) lstm_out = lstm_out.permute(1, 0, 2) # Transpose to (batch_size, seq_len, hidden_size * num_directions)[^4] fc_out = self.fc(lstm_out) # Apply linear transformation to adjust last dimension size return fc_out # Output shape: (batch_size, seq_len, output_dim) # Example usage input_tensor = torch.randn(10, 32, 5) # Shape: (seq_len, batch_size, input_size) model = CustomLSTM(input_size=5, hidden_size=8, output_dim=16, num_layers=1, bidirectional=True) output = model(input_tensor) print(output.shape) # Expected shape: (32, 10, 16), i.e., (batch_size, seq_len, d_model) ``` #### 关键点说明 - **`permute()` 方法**:用于改变张量的维度顺序,从而满足目标形状的要求。 - **`nn.Linear` 层**:当 `hidden_size` 不等于 `d_model` 时,此层负责完成最后的维度映射。 - **`batch_first` 参数**:设置为 `True` 将使输入和输出的第一个维度成为批次大小,但这会改变默认行为,需谨慎处理。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值