【问题标题】:How to create a custom loss function where intermediate training outputs(tensor y_pred) of an RNN, are fed to another predefined RNN?如何创建自定义损失函数,其中 RNN 的中间训练输出(张量 y_pred)被馈送到另一个预定义的 RNN?
【发布时间】:2019-11-11 17:17:05
【问题描述】:

我希望创建一个自定义损失函数,它不直接使用 RNN(y_pred) 的中间输出,而是将 y_pred 作为输入提供给另一个 RNN(比如 RNN2,它已经被定义和训练) ,并将这些预测值作为损失函数的参数。

我尝试从 model.compile 函数调用我的自定义损失函数,这会产生错误。是因为我无法将张量数据类型的对象输入 RNN2 吗?假设 y_pred 具有训练的中间输出,我错了吗? 使用 sess 的 y_pred 的简单打印命令也会引发错误! 即

sess=tf.Session()
print(sess.eval(y_pred))

那么问题是 y_pred 的基础吗?

不管怎样,这是代码:


def custom_loss(y_true, y_pred):
        predicted=rnn2.predict(y_pred)
        return K.mean(K.abs( predicted-y_true), axis=-1)

input_tensor = Input(shape=(1,1))
hidden = LSTM(100, activation='softmax',return_sequences=False)(input_tensor)
out = Dense(1, activation='softmax')(hidden)
model = Model(input_tensor, out)
model.compile(loss=custom_loss, optimizer='adam')

错误

You must feed a value for placeholder tensor 'input_19' with dtype float and shape [?,1,1]
     [[{{node input_19}}]]

【问题讨论】:

    标签: tensorflow keras


    【解决方案1】:

    这可能是您致电model.compile 时要做的事情。您是否尝试将它(RNN2)作为新层传递。

    RNN2.trainable = False #  [1]
    model = Sequential()
    model.add(RNN1)
    model.add(RNN2)
    
    def custom_loss(y_true, y_pred):
            # predicted=rnn2.predict(y_pred)
            return K.mean(K.abs( y_pred-y_true), axis=-1)
    
    

    编辑

    您能否详细说明我如何将模型(RNN2)用作 RNN1 中的层?

    如果是我,我会做这样的事情。

    from keras import models, layers
    
    
    inp = layers.Input((None, 1))
    x = layers.LSTM(512, return_sequences=True)(inp)
    x = layers.LSTM(256)(x)
    x = layers.Dense(32, name='rnn2_output')(x)
    rnn2 = models.Model(inp, x)
    rnn2.trainable = False #  [2]
    
    inp2 = layers.Input((None, 32))
    x = layers.LSTM(256, return_sequences=True)(inp2)
    x = layers.Dense(1)(x)
    x = rnn2(x)
    rnn1 = models.Model(inp2, x)
    rnn1.summary()
    
    

    注意,最近添加的代码 [2] 和旧代码 [1](最近编辑)都有 trainable = False,这意味着这个模型根本不会被训练。假设您将RNN2.predict 放入损失函数中。如果您还想训练它,请删除这些行。

    【讨论】:

    • rnn2 的输入应该是一个列表,但 y_pred 是一个张量。这不是问题吗?
    • 所以rnn2 不是 Keras 模型?
    • RNN2 是 Keras 模型
    • Keras 模型是否接受中间张量作为输入?我认为只有 numpy 数组才是 Keras 模型的合法输入
    • input 这个词在这里有 2(两种)含义。一种是调用fitpredict 之类的函数,另一种是创建模型时。
    猜你喜欢
    • 1970-01-01
    • 2018-07-07
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多