详解pytorch中循环神经网络(RNN、LSTM、GRU)的维度
RNN
torch.nn.rnn详解
torch.nn.RNN(input_size,
hidden_size,
num_layers=1,
nonlinearity=‘tanh’,
bias=True,
batch_first=False,
dropout=0.0,
bidirectional=False,
device=None,
dtype=None)
原理:
参数详解:
-
input_size – 输入x中预期特征的数量
-
hidden_size – 隐藏状态h中的特征数量
-
num_layers – 循环层数。例如,设置num_layers=2 意味着将两个LSTM堆叠在一起形成堆叠 LSTM,第二个 LSTM 接收第一个 LSTM 的输出并计算最终结果。默认值:1
-
nonlinearity– 使用的非线性。可以是’tanh’或’relu’。默认:‘tanh’
-
bias– 如果False,则该层不使用偏差权重b_ih和b_hh。默认:True
-
batch_first – 如果,则输入和输出张量以(batch, seq, feature)True形式提供,而不是(seq, batch, feature)。请注意,这不适用于隐藏状态或单元状态。默认:False
-
dropout – 如果非零,则在除最后一层之外的每个LSTM层的输出上 引入Dropout层,dropout 概率等于 。默认值:0.0
-
bidirectional – 如果True, 则成为双向LSTM。默认:False
RNN输入输出维度
rnn = nn.RNN(10, 20, 2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
output, hn = rnn(input, h0)
可以看到输入是x
和h_0
,h_0
可以是None。如果batch_size是第0维度,需设置batch_first=True
。
输出则是output
和h_n
。h_n存了每一层的t时刻的隐藏状态值
# Efficient implementation equivalent to the following with bidirectional=False
def forward(x, h_0=None