首页 > 解决方案 > 为什么在 LSTM 中添加 relu 激活后会得到 Nan?

问题描述

我有一个简单的 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% 可重现的。

标签: pythontensorflowlstmrelu

解决方案


当您使用relu activation functioninside 时lstm cell,可以保证单元的所有输出以及单元状态都是严格>= 0的。正因为如此,你的渐变变得非常大并且正在爆炸。例如,运行以下代码片段并观察输出是 never < 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))

推荐阅读