gru_unit

paddle.fluid.layers. gru_unit ( input, hidden, size, param_attr=None, bias_attr=None, activation='tanh', gate_activation='sigmoid', origin_mode=False ) [源代码]

Gated Recurrent Unit(GRU)循环神经网络计算单元。该OP用于完成单个时间步内GRU的计算,支持以下两种计算方式:

如果origin_mode为True,则使用的运算公式来自论文 Learning Phrase Representations using RNN Encoder Decoder for Statistical Machine Translation

ut=actg(Wuxxt+Wuhht1+bu)rt=actg(Wrxxt+Wrhht1+br)~ht=actc(Wcxxt+Wch(rtht1)+bc)ht=utht1+(1ut)~ht

如果origin_mode为False,则使用的运算公式来自论文 Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling

公式如下:

ut=actg(Wuxxt+Wuhht1+bu)rt=actg(Wrxxt+Wrhht1+br)~ht=actc(Wcxxt+Wch(rtht1)+bc)ht=(1ut)ht1+ut~ht

其中, xt 为当前时间步的输入,这个输入并非 input,该OP不包含 Wuxxt,Wrxxt,Wcxxt 的计算,注意 要在该OP前使用大小为GRU隐单元数目的3倍的全连接层并将其输出作为 inputht1 为前一时间步的隐状态 hiddenutrt~htht 分别代表了GRU单元中update gate(更新门)、reset gate(重置门)、candidate hidden(候选隐状态)和隐状态输出; 为逐个元素相乘; Wuh,buWrh,brWch,bc 分别代表更新门、重置门和候选隐状态在计算时使用的权重矩阵和偏置。在实现上,三个权重矩阵合并为一个 [D,D×3] 形状的Tensor存放,三个偏置拼接为一个 [1,D×3] 形状的Tensor存放,其中 D 为隐单元的数目;权重Tensor存放布局为: WuhWrh 拼接为 [D,D×2] 形状位于前半部分,Wch[D,D] 形状位于后半部分。

参数:
  • input (Variable) – 表示经线性变换后当前时间步的输入,是形状为 [N,D×3] 的二维Tensor,其中 N 为batch_size, D 为隐单元的数目。数据类型为float32或float64。

  • hidden (Variable) – 表示上一时间步产生的隐状态,是形状为 [N,D] 的二维Tensor,其中 N 为batch_size, D 为隐单元的数目。数据类型与 input 相同。

  • size (integer) – 输入数据 input 特征维度的大小,需要是隐单元数目的3倍。

  • param_attr (ParamAttr,可选) – 指定权重参数属性的对象。默认值为None,表示使用默认的权重参数属性。具体用法请参见 ParamAttr

  • bias_attr (ParamAttr,可选) - 指定偏置参数属性的对象。默认值为None,表示使用默认的偏置参数属性。具体用法请参见 ParamAttr

  • activation (string) – 公式中 actc 激活函数的类型。支持identity、sigmoid、tanh、relu四种激活函数类型,默认为tanh。

  • gate_activation (string) – 公式中 actg 激活函数的类型。支持identity、sigmoid、tanh、relu四种激活函数类型,默认为sigmoid。

  • origin_mode (bool) – 指明要使用的GRU计算方式,两种计算方式具体差异见公式描述,默认值为False。

返回:Variable的三元组,包含三个与 input 相同数据类型的Tensor,分别表示下一时间步的隐状态( ht )、重置的前一时间步的隐状态( rtht1 )和 ht,rt,~ht 的拼接,形状分别为 [N,D][N,D][N,D×3] 。通常只有下一时间步的隐状态( ht )作为GRU的输出和隐状态使用,其他内容只是中间计算结果。

返回类型: tuple

代码示例

import paddle.fluid as fluid

dict_dim, emb_dim = 128, 64
data = fluid.data(name='step_data', shape=[None], dtype='int64')
emb = fluid.embedding(input=data, size=[dict_dim, emb_dim])
hidden_dim = 512
x = fluid.layers.fc(input=emb, size=hidden_dim * 3)
pre_hidden = fluid.data(
    name='pre_hidden', shape=[None, hidden_dim], dtype='float32')
hidden = fluid.layers.gru_unit(
    input=x, hidden=pre_hidden, size=hidden_dim * 3)