【问题标题】:Why am I getting Nan after adding relu activation in LSTM?为什么在 LSTM 中添加 relu 激活后会得到 Nan?
【发布时间】:2019-03-24 10:46:40
【问题描述】:

我有一个简单的 LSTM 网络,大致如下:

lstm_activation = tf.nn.relu

cells_fw = [LSTMCell(num_units=100, activation=lstm_activation), 
            LSTMCell(num_units=10, activation=lstm_activation)]

stacked_cells_fw = MultiRNNCell(cells_fw)

_, states = tf.nn.dynamic_rnn(cell=stacked_cells_fw,
                              inputs=embedding_layer,
                              sequence_length=features['length'],
                              dtype=tf.float32)

output_states = [s.h for s in states]
states = tf.concat(output_states, 1)

我的问题是。当我不使用激活 (activation=None) 或使用 tanh 时,一切正常,但是当我切换 relu 时,我不断收到“训练期间的 NaN 损失”,这是为什么呢?它是 100% 可重现的。

【问题讨论】:

    标签: python tensorflow lstm relu


    【解决方案1】:

    当您在lstm cell 中使用relu activation function 时,可以保证单元格的所有输出以及单元格状态都将严格为>= 0。正因为如此,你的渐变变得非常大并且正在爆炸。例如,运行以下代码 sn-p 并观察输出永远不会是< 0

    X = np.random.rand(4,3,2)
    lstm_cell = tf.nn.rnn_cell.LSTMCell(5, activation=tf.nn.relu)
    hidden_states, _ = tf.nn.dynamic_rnn(cell=lstm_cell, inputs=X, dtype=tf.float64)
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    print(sess.run(hidden_states))
    

    【讨论】:

    • 感谢您的解释!所以它可以在没有任何激活的情况下工作,因为单元格可以具有
    • Noup。默认情况下,单元格内的激活函数为tanh。换句话说,如果您在定义单元格时不提供任何激活函数,它将默认使用tanh。另一方面,在没有激活函数(或线性激活函数)的情况下,由于细胞缺乏非线性,细胞的学习能力将降低为线性函数。
    猜你喜欢
    • 2018-08-08
    • 2022-11-14
    • 2020-01-22
    • 2023-03-15
    • 2016-03-03
    • 2016-09-23
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多