torch.nn.RNN()
RNN() 里面的参数有
input_size 表示输入 xt 的特征维度
hidden_size 表示输出的特征维度
num_layers 表示网络的层数
nonlinearity 表示选用的非线性激活函数,默认是 ‘tanh’
bias 表示是否使用偏置,默认使用
batch_first 表示输入数据的形式,默认是 False,就是这样形式,(seq, batch, feature),也就是将序列长度放在第一位,batch 放在第二位
dropout 表示是否在输出层应用 dropout
bidirectional 表示是否使用双向的 rnn,默认是 False
对于 RNNCell(),里面的参数就少很多,只有 input_size,hidden_size,bias 以及 nonlinearity
简单RNN的Pytorch实现
import torch
from torch.autograd import Variable
from torch import nn
# 调用nn.RNN建立模型
basic_rnn = nn.RNN(input_size=20, hidden_size=50, num_layers=2)
# print(basic_rnn.weight_hh_l0) # 访问其中参数
# 输入20维,输出50维,2层单向网络
# 建立网络接收的输入,序列输入toy_input和记忆输入h_0
toy_input = Variable(torch.randn(100, 32, 20)) # (seq, batch, feature),feature是特征维度
# 长度100、批量32、维度20
h_0 = Variable(torch.randn(2, 32, 50)) # (layer*direction, batch, hidden_size)
# 层数乘以方向,单向1,双向2;批量32,维度50
# 建立网络的输出,实际输出toy_output和记忆单元h_n
toy_output, h_n = basic_rnn(toy_input, h_0) # 将输入和隐藏状态传入网络
print(toy_output.size()) # torch.Size([100, 32, 50])
print(h_n.size()) # torch.Size([2, 32, 50])
简单LSTM的Pytorch实现
本质上和RNN一样,只不过内部计算更复杂、参数更多、输入和输出的数目也更多。
参数个数是标准RNN的4倍,因其内部多比RNN多了3个线性变化σ。
同时,隐藏状态比RNN多了C_0。
import torch
from torch.autograd import Variable
from torch import nn
lstm = nn.LSTM(input_size=20, hidden_size=50, num_layers=2)
# print(lstm.weight_ih_l0)
toy_input = Variable(torch.randn(100, 32, 20))
# 传入隐藏状态(h_0和c_0),随机生成张量
h_0 = Variable(torch.randn(2, 32, 50))
c_0 = Variable(torch.randn(2, 32, 50))
lstm_out, (h_n, c_n) = lstm(toy_input, (h_0, c_0))
# 注意写的时候,要把h和c括号括起来
# 不传入隐藏状态,就会默认传入参数全是0的h_0和c_0
# lstm_out, (h_n, c_n) = lstm(toy_input)
print(lstm_out.size()) # torch.Size([100, 32, 50])
print(h_n.size()) # torch.Size([2, 32, 50])
print(c_n.size()) # torch.Size([2, 32, 50])
简单GRU的Pytorch实现
本质上和LSTM是一样的。不同在于,隐藏状态参数是标准RNN的3倍,隐藏状态只有h0,没有c0。
import torch
from torch.autograd import Variable
from torch import nn
gru = nn.GRU(input_size=20, hidden_size=50, num_layers=2)
gru_input = Variable(torch.randn(100, 32, 20))
h_0 = Variable(torch.randn(2, 32, 50))
gru_output, h_t = gru(gru_input, h_0)
print(gru_output.size()) # torch.Size([100, 32, 50])
print(h_t.size()) # torch.Size([2, 32, 50])
RNNCell、LSTMCell、GRUCell是三个函数的单步版本,是一个序列中的一步,是循环神经网络中的一个循环。在序列的应用上更加灵活。