Pytorch 中 LSTM 和 LSTMCell 的区别

LSTM 的官方文档在这里

在这里插入图片描述

在例子中:
LSTM 函数的参数为输入特征向量的长度 input_size = 10、隐藏层向量的长度 hidden_size = 20、隐藏层的数量 num_layers = 2;
输入 input 的维度是时间/序列长度(句子有多少个单词) time_steps = 5、批量 batch = 3、输入特征向量的长度 input_size = 10;
初始的隐藏层向量与状态向量的维度都是隐藏层的数量 num_layers = 2、批量 batch = 3、隐藏层向量的长度 hidden_size = 20

在这里插入图片描述

LSTM 就是中间的红色框,它将输入(蓝色框)和初始的隐藏层向量与状态向量(黄色框)作为输入,输出的是最终的隐藏层向量与状态向量(绿色框)。

LSTMCell 的官方文档在这里

在这里插入图片描述
在例子中:
LSTMCell 函数的参数为输入特征向量的长度 input_size = 10、隐藏层向量的长度 hidden_size = 20;
输入 input 的维度是时间/序列长度(句子有多少个单词) time_steps = 5、批量 batch = 3、输入特征向量的长度 input_size = 10;
初始的隐藏层向量与状态向量的维度都是批量 batch = 3、隐藏层向量的长度 hidden_size = 20

在这里插入图片描述
对比即可得知,LSTMCell 就是图中的红色框,实际上就是一个隐藏层神经元,所以它没有 LSTM 中隐藏层数量这个参数。使用 LSTMCell 的方法就是 for 循环,遍历次数为时间/序列长度;LSTM 则是优化了这个 for 循环。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
PyTorch的BiLSTM是一种双向长短期记忆(Bi-directional Long Short-Term Memory)模型,可以用于序列数据的建模和处理。BiLSTM结合了正向和反向两个LSTM网络,其正向LSTM按照时间顺序处理输入序列,而反向LSTM按照时间逆序处理输入序列。这种结构允许模型同时利用过去和未来的上下文信息。 在PyTorch,可以使用`torch.nn.LSTM`和`torch.nn.LSTMCell`来实现BiLSTM模型。`torch.nn.LSTM`是一个多层LSTM模型的封装,而`torch.nn.LSTMCell`是一个单层LSTM模型的封装。 以下是一个使用BiLSTM模型进行文本分类的示例代码: ```python import torch import torch.nn as nn class BiLSTM(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(BiLSTM, self).__init__() self.hidden_dim = hidden_dim self.lstm = nn.LSTM(input_dim, hidden_dim, bidirectional=True) self.fc = nn.Linear(hidden_dim*2, output_dim) def forward(self, input): output, _ = self.lstm(input) output = self.fc(output[:, -1, :]) return output # 定义模型的输入维度、隐藏层维度和输出维度 input_dim = 100 hidden_dim = 50 output_dim = 10 # 创建BiLSTM模型实例 model = BiLSTM(input_dim, hidden_dim, output_dim) # 构造输入数据 input = torch.randn(5, 3, input_dim) # 输入维度为(序列长度, 批次大小, 输入维度) # 运行模型 output = model(input) print(output.size()) # 输出维度为(序列长度, 批次大小, 输出维度) ``` 这段代码定义了一个BiLSTM模型类`BiLSTM`,模型的输入维度为`input_dim`,隐藏层维度为`hidden_dim`,输出维度为`output_dim`。在`forward`方法,首先使用`nn.LSTM`进行双向LSTM计算,然后通过线性层`nn.Linear`将输出转换为最终的预测结果。最后,可以通过输入数据调用模型来进行预测。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值