11-循环神经网络

回顾 DNN

image-20210319095253370

稠密网络(全连接)/深度神经网络。

什么是RNN

RNN可以处理序列关系的数据。

序列关系数据:自然语言,天气预测……

image-20210319102149594

RNN Cell的本质是一个线性层,和以往的线性层,区别是线性层是共享的。其中$h_0$为先验,如果没有数据输入,则随机初始化,经过一次RNN Cell得到$h_1$,在下一次的时候,输出的$h_1$又会被当成输入,进行下一次循环。

伪代码:

image-20210319103432450

RNN in Pytorch

调用RNN Cell

定义

hiddent = cell(input,hidden)中,输入的形式为:

  • input:input of shape(batch,input_size)

  • hidden:hidden of shape(batch,hidden_size)

输出的形式为:

  • hidden:hidden of shape(batch,hidden_size)

image-20210319105327932

如何使用RNN Cell

假设我们有具有以下性质的序列:

  • batchSize = 1,即N=1

  • seqLen = 3,即$x_1$,$x_2$,$x_3$

  • inputSize = 4,即为四维的向量

  • hiddenSize = 2,即隐藏层设置为2维

所以,RNNCell的输入输出形状如下:

  • input.shape = (batchSize,inputSize)

  • output.shape = (batchSize,hiddenSize)

整个序列,构造如下:

  • dataset.shape = (seqLen,batchSize,inputSize)

注意,cell是公用的,$h_0$是先验的或者全0

如何使用 RNN

其中num_layers表示层数,注意层数选择,RNN计算十分耗时的;inputs包括整个的输入序列。

image-20210319123206758
image-20210319123638022
image-20210319123741294
image-20210319123801494
image-20210319130242600

实例

  • 训练模型去学习:hello $\rightarrow$ ohlol

image-20210319130852666

自定义RNN Cell

最后更新于

这有帮助吗?