import torch
rnn_cell = torch.nn.RNNCell(5, 10)
input = torch.randn(2, 5)
h_0 = torch.randn(2, 10)
h = rnn_cell(input, h_0)
print(h.shape)
rnn = torch.nn.RNN(input_size=6, hidden_size=12, num_layers=2)
input = torch.randn(4, 24, 6)
h_0 = torch.randn(2, 24, 12)
output, hn = rnn(input, h_0)
print(output.size(), hn.size())
单向LSTM输入输出的理解
from torch import nn
lstm = nn.LSTM(input_size=300, hidden_size=200, batch_first=True, num_layers=1)
# 这里因为下面 sequence_length=20, lstm并且层数是1,所以创建了20个lstm的细胞
x = torch.randn((8, 20, 300))
print(x.shape)
# torch.Size([8, 20, 200]) 分别是 batch_size, sequence_length, embedding_dim
y, (h, c) = lstm(x)
print(y.shape)
# torch.Size([8, 20, 200]) 分别是 batch_size, sequence_length, hidden_size
# 保存最后一层每一个timestep输出的h
print(h.shape)
# torch.Size([1, 8, 200]) 分别是 num_layers, batch_size, hidden_size
# 保存每一层,最后一个timestamp输出的h
print(c.shape)
# torch.Size([1, 8, 200]) 分别是 num_layers, batch_size, hidden_size
# 保存每一层,最后一个timestamp输出的c,所以形状和h一样的,但是数值不一样
双向LSTM输入输出的理解
from torch import nn
lstm = nn.LSTM(input_size=300, hidden_size=200, batch_first=True, num_layers=1, bidirectional=True)
# 这里因为下面 sequence_length=20, lstm并且层数是1,所以创建了20个lstm的细胞
x = torch.randn((8, 20, 300))
print(x.shape)
# torch.Size([8, 20, 200]) 分别是 batch_size, sequence_length, embedding_dim
y, (h, c) = lstm(x)
print(y.shape)
# torch.Size([8, 20, 400]) 分别是 batch_size, sequence_length, hidden_size*2 (双向)
# 保存最后一层每一个timestep输出的h
print(h.shape)
# torch.Size([2, 8, 200]) 分别是 num_layers*2(双向), batch_size, hidden_size
# 保存每一层,最后一个timestamp输出的h
print(c.shape)
# torch.Size([1, 8, 200]) 分别是 num_layers*2(双向), batch_size, hidden_size
# 保存每一层,最后一个timestamp输出的c,所以形状和h一样的,但是数值不一样