本文参考了:
pytorch中的nn.LSTM模块参数详解人人都能看懂的LSTMtorch.nn.LSTM()函数维度详解
lstm示意图
右侧为LSTM示意图
torch.nn.lstm(input_size,hidden_size,num_layers,bias,batch_first,dropout,bidirectional)
参数
- input_size:输入的维度=embedding_size
- hidden_size:h的维度
- num_layers:堆叠LSTM的层数,默认值为1
- bias:隐层状态是否带bias,默认为true。bias是偏置值,或者偏移值。没有偏置值就是以0为中轴,或以0为起点。
- batch_first:如果设置为 True,则输入数据的维度中第一个维度就 是 batch 值,默认为 False。更详细的在Pytorch的参数“batch_first”的理解中
- dropout:默认值0。是否在除最后一个 RNN 层外的其他 RNN 层后面加 dropout 层。输入值是 0-1 之间的小数,表示概率。0表示0概率dripout,即不dropout
- bidirectional:是否双向传播,默认值为False
dropout
dropout:dropout顾名思义就是被拿掉的意思,正因为我们在神经网络当中拿掉了一些神经元,所以才叫做dropout层。为了防止过拟合。
在进行第一个batch的训练时,有以下步骤:
- 设定每一个神经网络层进行dropout的概率
- 根据相应的概率拿掉一部分的神经元,然后开始训练,更新没有被拿掉神经元以及权重的参数,将其保留
- 参数全部更新之后,又重新根据相应的概率拿掉一部分神经元,然后开始训练,如果新用于训练的神经元已经在第一次当中训练过,那么我们继续更新它的参数。而第二次被剪掉的神经元,同时第一次已经更新过参数的,我们保留它的权重,不做修改,直到第n次batch进行dropout时没有将其删除。
#num_layers
import torch.nn as nn
import torch
x = torch.rand(10,24,100)
#torch.nn.lstm(input_size=100,hidden_size=16,num_layers=2)
#输入维度100,h维度16,lstm层数2
#以训练句子为例子,假如每个词是100维的向量,每个句子含有24个单词,一次训练10个句子。
#那么batch_size=10,seq=24,input_size=100。(seq指的是句子的长度,input_size作为一个x_t的输入)
lstm = nn.LSTM(100,16,num_layers=2)
output,(h,c) = lstm(x)
print(output.size())
print(h.size())
print(c.size())
torch.Size([10, 24, 16])
torch.Size([2, 24, 16])
torch.Size([2, 24, 16])
#num_layers,bidirectional
import torch.nn as nn
import torch
x = torch.rand(10,24,100)
lstm = nn.LSTM(100,16,bidirectional=True)
output,(h,c) = lstm(x)
print(output.size())
print(h.size())
print(c.size())
torch.Size([10, 24, 32])
torch.Size([2, 24, 16])
torch.Size([2, 24, 16])
import torch.nn as nn
import torch
x = torch.rand(10,24,100) #batch,seq,input_size
h0 = torch.rand(1,24,16)# num_layers*num_directions, batch, hidden_size
c0 = torch.rand(1,24,16)
lstm = nn.LSTM(100,16)
output,(h,c) = lstm(x,(h0,c0))
print(output.size())
print(h.size())
print(c.size())
torch.Size([10, 24, 16])
torch.Size([1, 24, 16])
torch.Size([1, 24, 16])
最后附上参数维度:
解释一下,第一行是构建lstm时的输入维度,后边几行是lstm用到的参数由输入维度推出来的维度
如果是双向num_directions=2,否则num_directions=1
参数 | 维度1 | 维度2 | 维度3 |
lstm=nn.LSTM | input_size | hidden_size | num_layers |
x | seq_len | batch | input_size |
h0 | num_layers×num_directions | batch | hidden_size |
c0 | num_layers×num_directions | batch | hidden_size |
output | seq_len | batch | num_directions×hidden_size |
hn | num_layers×num_directions | batch | hidden_size |
cn | num_layers×num_directions | batch | hidden_size |