pytorch nn.LSTM详解 代码里有详细的参数说明

nn.LSTM(in_dim, hidden_dim, n_layer, batch_first=True):LSTM循环神经网络
参数:
input_size: 表示的是输入的矩阵特征数
hidden_size: 表示的是输出矩阵特征数
num_layers 表示堆叠几层的LSTM,默认是1
bias: True 或者 False,决定是否使用bias
batch_first: True 或者 False,因为nn.lstm()接受的数据输入是(序列长度,batch,输入维数),这和我们cnn输入的方式不太一致,所以使用batch_first,我们可以将输入变成(batch,序列长度,输入维数)
dropout: 表示除了最后一层之外都引入一个dropout
bidirectional: 默认是false,代表不用双向LSTM,双向LSTM,也就是序列从左往右算一次,从右往左又算一次,这样就可以两倍的输出

举个例子:
对句子进行LSTM操作

假设有100个句子(sequence),每个句子里有5个词,batch_size=3,embedding_size=10

此时,各个参数为:
input_size=embedding_size=10
batch=batch_size=3
seq_len=5

另外设置hidden_size=20, num_layers=1

import torch
import torch.nn as nn
from torch.autograd import Variable

rnn = nn.LSTM(input_size=10,hidden_size=20,num_layers=2)#输入向量维数10, 隐藏元维度20, 2个LSTM层串联(若不写则默认为1)
inputs = torch.randn(5,3,10)#输入(seq_len, batch_size, input_size) 序列长度为5 batch_size为3 输入维度为10
h_0 = torch.randn(2,3,20)#(num_layers * num_directions, batch, hidden_size)  num_layers = 2 ,batch_size=3 ,hidden_size = 20,如果LSTM的bidirectional=True,num_directions=2,否则就是1,表示只有一个方向
c_0 = torch.randn(2,3,20)#c_0和h_0的形状相同,它包含的是在当前这个batch_size中的每个句子的初始细胞状态。h_0,c_0如果不提供,那么默认是0
num_directions=1#   因为是单向LSTM

#输出格式为(output,(h_n,c_n))
output,(h_n,c_n) = rnn(inputs,(h0,c0))#输入格式为lstm(input,(h_0, c_0))
print("out:", output.shape)
print("h_n:", h_n.shape)
print("c_n:", c_n.shape)

输出结果:
out: torch.Size([5, 3, 20])
h_n: torch.Size([2, 3, 20])
c_n: torch.Size([2, 3, 20])

输出结果说明:
output的shape为(seq_len=5,batch_size=3,num_directions*hidden_size),hidden_size为20,num_directions为1。它包含的LSTM的最后一层的输出特征(h_t),t是batch_size中每个句子的长度。

h_n.shape为(num_directions * num_layers=2,batch_szie=3,hidden_size=20)

c_n.shape==h_n.shape

h_n包含的是句子的最后一个单词的隐藏状态,c_n包含的是句子的最后一个单词的细胞状态,所以它们都与句子的长度seq_len无关。
output[-1]与h_n是相等的,因为output[-1]包含的正是batch_size个句子中每一个句子的最后一个单词的隐藏状态,注意LSTM中的隐藏状态其实就是输出,cell state细胞状态才是LSTM中一直隐藏的,记录着信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值