pytorch lstm

1、输入input:数据维度是 (seq, batch, feature),即序列长度、batch_size、每个时刻特征数量。

2、output, (hn, cn) = nn.LSTM(input_size, hidden_size, num_layers)

input_size:每时刻输入特征数量

hidden_size:隐藏层特征数量,决定着输出每一时刻的特征维度

num_layers:隐藏层数量

output:输出结果,维度为(seq, batch_size,hidden_size),相比于输入而言,输出的时间长度和batch_size都不变,只有特征维度发生变化,与设置的隐藏状态数一致。

hn:最后一个时刻的隐藏状态,每一层都会有一个最后时刻的隐藏状态,因此它的维度为(num_layers,batch_size,hidden_size)。

cn:最后一个时刻的记忆单元状态,每一层都会有一个最后时刻的状态,因此它的维度也为(num_layers,batch_size,hidden_size)。

关于output和hn,output为最后一层所有时刻的隐藏状态输出,而hn为最后一个时刻的所有层的隐藏状态输出。因此,可以得到output[-1] = hn[-1]。

3、注意事项,与CNN不同的是batch_size在中间,而CNN通常Batch_size在第一个维度,可通过batch_first=True设置与CNN保持一致。

5、双向LSTM,设置bidirectional=True。与单向lstm区别在于,output的特征维度增加一倍,维度变为(seq, batch_size,2*hidden_size),层数也相当于增加了一倍,即每一层都会相应增加一层逆向推理的层,那么hn和cn的一个维度加倍,即(2*num_layers,batch_size,hidden_size)。由于双向lstm先从左到右再从右到左,因此hn的输出反而与output的第一个维度相等,output[0,:,hidden_size:] = hn[-1]。

4、示例代码

import numpy as np
from torch import nn
import torch

x = torch.randn(13, 7, 3)#seq length 13, batch size 7, features 3
lstm = nn.LSTM(3, 5, 2)
output, (hn, cn) = lstm(x)
print('input shape: ', x.shape)          #13,7,3
print('output shape: ', output.shape)    #13,7,5
print('hn shape: ', hn.shape)            #2,7,5
print('cn shape: ', cn.shape)            #2,7,5
#print(output[-1]) 
#print(hn[-1])
print(output[-1] == hn[-1])              #True, 二者相等

#batch_first=True
x = torch.randn(13, 7, 3)#seq length 7, batch size 13, features 3
lstm = nn.LSTM(3, 5, 2, batch_first=True) #batch size 13
output, (hn, cn) = lstm(x)
print('input shape: ', x.shape)          #13,7,3
print('output shape: ', output.shape)    #13,7,5
print('hn shape: ', hn.shape)            #2,13,5
print('cn shape: ', cn.shape)            #2,13,5
#print(output[:,-1,:])                    #在序列维度上的最后一维
#print(hn[-1,])
print(output[:,-1,:] == hn[-1])         #True, 二者相等

#bidirectional=True
x = torch.randn(13, 7, 3)#seq length 13, batch size 7, features 3
lstm = nn.LSTM(3, 5, 2, bidirectional=True)
output, (hn, cn) = lstm(x)
print('input shape: ', x.shape)          #13,7,3
print('output shape: ', output.shape)    #13,7,10
print('hn shape: ', hn.shape)            #4,7,5
print('cn shape: ', cn.shape)            #4,7,5
print(output[-1]) 
print(hn[-1])
print(output[0, :, 5:] == hn[-1])      #True, 二者相等,由于双向lstm先从左到右再从右到左,因此hn的输出反而与output的第一个维度相等。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coding的叶子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值