如何在RNN中应用层规范化凯拉斯?

2024-05-13 03:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把layer normalization应用到递归神经网络特斯拉斯. 在TensorFlow 2.0中,tf.layers.experimental中有一个LayerNormalization类,但不清楚在每个时间步,如何在一个递归层(如LSTM)内使用它。我应该创建一个自定义单元格,还是有更简单的方法?在

例如,在每个时间步应用dropout就像在创建LSTM层时设置recurrent_dropout参数一样简单,但是没有recurrent_layer_normalization参数。在


Tags: 方法layer参数layerstftensorflow时间神经网络
1条回答
网友
1楼 · 发布于 2024-05-13 03:18:49

您可以通过继承SimpleRNNCell类来创建自定义单元格,如下所示:

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.activations import get as get_activation
from tensorflow.keras.layers import SimpleRNNCell, RNN, Layer
from tensorflow.keras.layers.experimental import LayerNormalization

class SimpleRNNCellWithLayerNorm(SimpleRNNCell):
    def __init__(self, units, **kwargs):
        self.activation = get_activation(kwargs.get("activation", "tanh"))
        kwargs["activation"] = None
        super().__init__(units, **kwargs)
        self.layer_norm = LayerNormalization()
    def call(self, inputs, states):
        outputs, new_states = super().call(inputs, states)
        norm_out = self.activation(self.layer_norm(outputs))
        return norm_out, [norm_out]

这个实现运行一个常规的SimpleRNN单元一个步骤,没有任何activation,然后对结果输出应用层规范,然后应用activation。你可以这样使用它:

^{pr2}$

对于GRU和LSTM单元,人们通常在门上应用层规范(在输入和状态线性组合之后,在sigmoid激活之前),所以实现起来有点困难。或者,在应用activationrecurrent_activation之前应用layer norm可能会得到很好的结果,这将更容易实现。在

相关问题 更多 >