如何在Keras自定义损失函数中使用张量?

问题描述

我需要训练具有自定义损失函数的模型,该模型还将在预测后立即更新某些外部函数,如下所示:

def loss_fct(y_true,y_pred):
    global Feeder
 
    # Change values of Feeder given y_pred
    for value in y_pred:
        Feeder.do_something(value)
    
    return K.mean(y_true - y_pred,axis=-1)

但是这不起作用,因为TF无法遍历AutoGraph中的张量:

OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.

我的模特看起来像这样

model = Sequential()
model.add(Input(shape=(DIM,)))
model.add(Dense(DIM,activation=None))
model.add(Dense(16,activation=None))
model.add(Dense(4,activation="softmax"))
model.compile(optimizer="adam",loss=loss_fct)
model.summary()

它是这样训练的:

model.fit(x=Feeder.Feed,epochs=18,verbose=1,callbacks=None,)

Feeder.Feed生成2个NumPy数组的生成器。


解决方法

经过大量研究,我发现this answer。该方法似乎没什么问题,但是它是一个Tensorflow >= 2.2.0错误,默认情况下启用了Eager Execution

最后,要解决此问题,请使用model.compile(...,run_eagerly=True),并且可以在训练期间进行迭代和访问张量。