mindspore.nn.RNN

查看源文件
class mindspore.nn.RNN(*args, **kwargs)[源代码]

循环神经网络(RNN)层,将具有 tanhReLU 非线性的RNN层应用到输入。

对输入序列中的每个元素,每层的计算公式如下:

ht=activation(Wihxt+bih+Whhh(t1)+bhh)

这里的 ht 是在 t 时刻的隐藏状态, xt 是在 t 时刻的输入, h(t1) 是上一层在 t1 时刻的隐藏状态,或初始隐藏状态, Wih 是每层RNN输入(input gate)计算的weight, bih 是对应的bias, Whh 是每层RNN隐藏状态(hidden state)计算的weight, bhh 是对应的bias。

参数:
  • input_size (int) - 输入层输入的特征向量维度。

  • hidden_size (int) - 隐藏层输出的特征向量维度。

  • num_layers (int) - 堆叠RNN的层数。默认值: 1

  • nonlinearity (str) - 用于选择非线性激活函数。取值可为'tanh'或'relu'。默认值: 'tanh'

  • has_bias (bool) - Cell是否有偏置项 bihbhh 。默认值: True

  • batch_first (bool) - 指定输入 x 的第一个维度是否为batch_size。默认值: False

  • dropout (float) - 指的是除第一层外每层输入时的Dropout概率。Dropout的范围为[0.0, 1.0)。默认值: 0.0

  • bidirectional (bool) - 指定是否为双向RNN,如果bidirectional=True,则num_directions=2,否则为1。默认值: False

  • dtype (mindspore.dtype) - Parameters的dtype。默认值: mstype.float32

输入:
  • x (Tensor) - 数据类型为mindspore.float32或mindspore.float16,shape为 (seq_len,batch_size,input_size)(batch_size,seq_len,input_size) 的Tensor。

  • hx (Tensor) - 数据类型为mindspore.float32或mindspore.float16,shape为 (num_directionsnum_layers,batch_size,hidden_size) 的Tensor。

  • seq_length (Tensor) - 输入batch的序列长度,Tensor的shape为 (batch_size) 。此输入指明真实的序列长度,以避免使用填充后的元素计算隐藏状态,影响最后的输出。当 x 被填充元素时,建议使用此输入。默认值: None

输出:

Tuple,包含(output, hx_n)的tuple。

  • output (Tensor) - shape为 (seq_len,batch_size,num_directionshidden_size)(batch_size,seq_len,num_directionshidden_size) 的Tensor。

  • hx_n (Tensor) - shape为 (num_directionsnum_layers,batch_size,hidden_size) 的Tensor。

异常:
  • TypeError - input_sizehidden_sizenum_layers 不是int。

  • TypeError - has_biasbatch_firstbidirectional 不是bool。

  • TypeError - dropout 不是float。

  • ValueError - dropout 不在[0.0, 1.0)范围内。

  • ValueError - nonlinearity 不在['tanh', 'relu']中。

支持平台:

Ascend GPU CPU

样例:

>>> import mindspore as ms
>>> import numpy as np
>>> net = ms.nn.RNN(10, 16, 2, has_bias=True, batch_first=True, bidirectional=False)
>>> x = ms.Tensor(np.ones([3, 5, 10]).astype(np.float32))
>>> h0 = ms.Tensor(np.ones([1 * 2, 3, 16]).astype(np.float32))
>>> output, hn = net(x, h0)
>>> print(output.shape)
(3, 5, 16)