【问题标题】:Pass inputs to loss function in eager mode在急切模式下将输入传递给损失函数
【发布时间】:2021-07-06 18:26:21
【问题描述】:

here窃取示例代码:

def custom_loss_wrapper(input_tensor):
    def custom_loss(y_true, y_pred):
        return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor)
    return custom_loss

input_tensor = Input(shape=(10,))
hidden = Dense(100, activation='relu')(input_tensor)
out = Dense(1, activation='sigmoid')(hidden)
model = Model(input_tensor, out)
model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam')

X = np.random.rand(1000, 10)
y = np.random.rand(1000, 1)
model.train_on_batch(X, y)

这在最近的 Tensorflow 版本中不再有效。我看到的主要解决方案是禁用急切执行,但这会破坏我正在做的其他事情。

如何在保持渴望模式时保持这种类型的功能?也就是说,将输入传递给损失函数?我能想到的最好的办法是修改网络以将输入连接到输出,然后在损失中将其拉开。不过很笨拙。

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    您可以使用add_loss 将外部层传递给您的损失,在您的情况下是输入张量。

    这里是一个例子:

    def CustomLoss(y_true, y_pred, input_tensor):
        return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor)
    
    X = np.random.uniform(0,1, (1000,10))
    y = np.random.randint(0,2, (1000,1))
    
    inp = Input(shape=(10,))
    hidden = Dense(100, activation='relu')(inp)
    out = Dense(1, activation='sigmoid')(hidden)
    target = Input((1,))
    model = Model([inp,target], out)
    
    model.add_loss( CustomLoss( target, out, inp ) )
    model.compile(loss=None, optimizer='adam')
    model.fit(x=[X,y], y=None, epochs=3)
    

    在推理模式下使用模型(从输入中删除目标)

    final_model = Model(model.input[0], model.output)
    final_model.predict(X)
    

    【讨论】:

    • 非常感谢您的回答,您结束了我的痛苦。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 2023-01-12
    • 1970-01-01
    • 2021-06-09
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多