1 复习一下 nn.RNN 的参数
- 参数介绍:
(1)input_size
: The number of expected features in the input x
(x的特征维数,比如说如果是一个单词用100d的向量来表示的话,那么input_size=100)
(2)hidden_size
: The number of features in the hidden state h
(表示隐藏层的特征维数,这个是自己指定的,而且是通过不断迭代来确定hidden_size 的取值的)
(3)num_layers
: Number of recurrent layers. 例如., setting num_layers=2
(就是说 RNN 的层数)【默认为1】
(4)bias
: 表示是否需要偏置量 bias weights b_ih
and b_hh
. 【默认是True】
(5)batch_first
:如果是batch_first, 则输入数据维度:(batch, seq, feature); 否则为 (seq, batch, feature)【默认为False】
(6)dropout
: 随机丢失一部分神经元。【默认为0,就是全保留全部神经元】
(7)bidirectional
: 是否是双向的RNN。【默认是False】
2 LSTM的 __init__函数
- 为什么要复习一下RNN 呢,就是因为这里LSTM的参数 基本上和RNN是一样的,加了一个(8)
(1)input_size
: The number of expected features in the input x
(x的特征维数,比如说如果是一个单词用100d的向量来表示的话,那么input_size=100)
(2)hidden_size
: The number of features in the hidden state h
(表示隐藏层的特征维数,这个是自己指定的,而且是通过不断迭代来确定hidden_size 的取值的)
(3)num_layers
: Number of recurrent layers. 例如., setting num_layers=2
(就是说 RNN 的层数)【默认为1】
(4)bias
: 表示是否需要偏置量 bias weights b_ih
and b_hh
. 【默认是True】
(5)batch_first
:如果是batch_first, 则输入数据维度:(batch, seq, feature); 否则为 (seq, batch, feature)【默认为False】
(6)dropout
: 随机丢失一部分神经元。【默认为0,就是全保留全部神经元】
(7)bidirectional
: 是否是双向的RNN。【默认是False】
(8)proj_size
: proj_size: If >0 will use LSTM with projections of corresponding size. 【默认为0】自己还没用过这里
3 LSTM.forward()
- 需要注意的是,传入的x的shape,而且这次要传入初始 h t 1 , c t 1 ht_1,ct_1 ht1,ct1
- 输出是两个,一个是out,还有一个是中间的
memory
,(ht, ct)
out, (ht, ct) = lstm(x, [ht_1, ct_1])
x
: [ seq, batch, word_vec] (这边batch_first=0), 和RNN 是一样的h和c
:[num_layer, batch, hidden_feature]out
: [seq, batch, hidden_feature]
4 动手写一个简单的lstm层
- 代码如下:
import torch
from torch import nn
lstm = nn.LSTM(input_size=100, hidden_size=20, num_layers=4)
print(lstm)
x = torch.randn(10, 3, 100) # [seq, b, word_vec]
out, (h, c) = lstm(x)
print(out.shape, h.shape, c.shape)
- 输出如下:
LSTM(100, 20, num_layers=4)
torch.Size([10, 3, 20]) torch.Size([4, 3, 20]) torch.Size([4, 3, 20])