如何对内部损失函数进行建模? Tensorflow,Keras

问题描述

在此答案之后,我正在尝试使用以下结构为回归问题构建自定义损失: Keras Custom loss function to pass arguments other than y_true and y_pred

现在,我的功能如下:

def CustomLoss(model,X_valid,y_valid,batch_size):
    def Loss(y_true,y_pred):
        n_samples=5
        mc_predictions = np.zeros((n_samples,256,256))
        for i in range(n_samples):
           y_p = model.predict(X_valid,verbose=1,batch_size=batch_size)
    (Other operations...) 
        return LossValue
    return Loss

尝试执行此行时 y_p = model.predict(X_valid,batch_size=batch_size)我收到以下错误

方法需要处于跨副本上下文中,请使用get_replica_context()。merge_call()

根据我收集的信息,我无法在损失函数中使用model.predict。是否有解决方法解决方案? 如果我的问题很明确,或者您需要任何其他信息,请告诉我。谢谢!

解决方法

听起来像您可以使用model.add_loss。您可以使用它在模型内部指定损失函数。它还消除了仅将y和y_pred引入损失函数的需要。 https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_loss \一些伪代码:

class YourModel(tf.keras.Model): 
    ...
    def call(self,inputs): 
        unpack,any,extra,stuff = inputs
        (your network code goes here)
        loss = (other operations)
        self.add_loss(loss)
        return output

(如果您不知道,model.predict基本上只是model.call,但附加了一些额外的花哨。)