【问题标题】:Gradients in Keras loss function with RNNs带有 RNN 的 Keras 损失函数中的梯度
【发布时间】:2019-12-06 04:43:36
【问题描述】:

我有一个简单的测试 LSTM 模型:

inputs = Input(shape=(k, m))
layer1 = LSTM(128, activation='relu', return_sequences=True)(inputs)
layer2 = LSTM(128, activation='relu')(layer1)
predictions = Dense(1, activation='linear')(layer2)
model = Model(inputs=inputs, outputs=predictions)

以及使用输出梯度 wrt 输入的自定义损失函数:

def custom_loss(model, input_tensor):
    def loss(y_true, y_pred):
        grads = K.gradients(model.output, model.input)[0] 
        loss_f = losses.mean_squared_error(y_true, y_pred) + K.exp(-K.sum(grads))
        return loss_f

return loss

模型训练失败并出现错误“不支持 while 循环的二阶梯度”:

model.compile(optimizer='adam', loss=custom_loss(model_reg, inputs_reg), metrics=['mean_absolute_error'])
model_reg.fit(x_train, y_train, batch_size=32, epochs=20, verbose=1, validation_data=(x_val, y_val)) 

-----
....
      159 
      160   if op_ctxt.grad_state:
-->   161     raise TypeError("Second-order gradient for while loops not supported.")
      162 
      163   if isinstance(grad, ops.Tensor):

TypeError: Second-order gradient for while loops not supported.

为什么 TF 在这里尝试计算二阶梯度?它应该只是第一顺序。

相同的损失函数适用于非 RNN 模型。

【问题讨论】:

  • 您正在计算grads 中的梯度,并将涉及它们的项添加到损失函数中。由于梯度下降需要损失的梯度,这将尝试计算梯度的梯度,即二阶梯度。

标签: tensorflow keras loss-function


【解决方案1】:

设置 Unroll 属性有助于解决问题:

layer1 = LSTM(128, activation='relu', return_sequences=True, unroll=True)(inputs)
layer2 = LSTM(128, activation='relu', unroll=True)(layer1)

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 2018-07-07
    • 2016-11-29
    • 2021-03-11
    • 2019-05-30
    • 1970-01-01
    • 2021-05-12
    • 2016-07-01
    相关资源
    最近更新 更多