学习笔记:RNN

RNN学习来源:刘二大人的视频

  • 卷积神经网络RNN

RNNCell

RNNCell
  • h_{t-1}是上一时刻的状态,大小为:hidden_size * hidden_size
  • x_t是当前时刻的输入,大小为:hidden_size * input_size
  • 得到的结果大小是hidden_size
  • 将上一时刻的状态和当前时刻的输入经过线性变化,然后通过激活函数
  • 由于在激活函数之前,其实就是线性变换,因此,一般都是将h_{t-1}x_t拼接,共用一个W,即如下所示.
    前面的矩阵W的大小为hidden_size * ( hidden_size + input_size)
    后面的矩阵为:( hidden_size + input_size) * 1
    W_{hh}h_{t-1} + W_{ih}x_t = [W_{hh} W_{ih} ]{ \left[ \begin{matrix} {h_{t-1}} \\ x_t \end{matrix} \right] }
  • 所以确定一个RNNCell只需要两个值。
  • pytorch中,数据默认第一个维度是batch_size,因此输入数据维度为:batch_size * input_size,隐藏层维度为:batch_size * hidden_size
cell = torch.nn.RNNCell(input_size=input_size,hidden_size=hidden_size)
hidden = cell(input, hidden)
  • 我们的输入的维度一般是:seq_Len * batch_size * input_sizeseqLen就是序列长度,RNNCell会一个一个的取出来进行输出
batch_size = 1
seq_len = 5
input_size = 4
hidden_size = 2
cell = nn.RNNCell(input_size=input_size, hidden_size=hidden_size)
dataset = torch.randn(seq_len, batch_size, input_size)
hidden = torch.zeros(batch_size, hidden_size)
for idx, inputs in enumerate(dataset):
    print('='*20, idx, '='*20)
    print('inputs shape:{0}|'.format(inputs.shape))
    
    hidden = cell(inputs, hidden)
    print('hidden shape:{0}'.format(hidden.shape))
    print(hidden)
# 输出如下:
==================== 0 ====================
inputs shape:torch.Size([1, 4])|
hidden shape:torch.Size([1, 2])
tensor([[ 0.5790, -0.7934]], grad_fn=<TanhBackward>)
==================== 1 ====================
inputs shape:torch.Size([1, 4])|
hidden shape:torch.Size([1, 2])
tensor([[ 0.6467, -0.4657]], grad_fn=<TanhBackward>)
==================== 2 ====================
inputs shape:torch.Size([1, 4])|
hidden shape:torch.Size([1, 2])
tensor([[0.2735, 0.6325]], grad_fn=<TanhBackward>)
==================== 3 ====================
inputs shape:torch.Size([1, 4])|
hidden shape:torch.Size([1, 2])
tensor([[0.0558, 0.4998]], grad_fn=<TanhBackward>)
==================== 4 ====================
inputs shape:torch.Size([1, 4])|
hidden shape:torch.Size([1, 2])
tensor([[-0.1049, -0.4924]], grad_fn=<TanhBackward>)

RNN 整体架构

  • 将RNNCell以循环的方式应用就可以构造成为RNN


    RNN
  • 左边是RNN整体架构,右边是拆开的架构
  • 刚开始时输入x_1h_0,其中x_1是输入序列的第一个单词或者字母,h_0是初始化的隐藏层
  • 经过第一轮计算,得到h_1,然后将h_1x_2送入RNNCell,又得到h_2,以此类推。。
  • 循环过程类似以下代码:
for x in X:
  h  = rnncell(x,h)
  • pytroch中的RNN
pytroch中的RNN
  • 其中num_layers代表的是RNN的层数


    num_layers
  • RNN维度


    RNN维度
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。