我正在尝试为用 Keras 编写的模型编写一个逐像素加权损失函数,但在 TensorFlow 2.0 中似乎不再可能了,即除了 y_true
之外不可能有其他输入的损失函数和y_pred
我以前是这样写的:
from tensorflow.keras.layers import Input, Conv2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import backend as K
def my_keras_model():
input = Input((256,256,1), name='input')
weight = Input((256,256,1), name='weights')
c1 = Conv2D(16, (3, 3), activation='relu', kernel_initializer='glorot_uniform', padding='same')(input)
outputs = Conv2D(1, (1, 1), activation='sigmoid')(c1)
model=Model(input=[input,weight], output=outputs)
model.compile(optimizer=Adam(learning_rate=0.001, name='adam'), loss=my_weighted_loss(weight))
return model
def my_weighted_loss(weight):
def loss(y_true, y_pred):
return K.mean(weight * K.binary_crossentropy(y_true, y_pred), axis=-1)
return loss
知道如何在 TF 2 中做到这一点吗?
最佳答案
实现此目的的一种“hacky”方法是将原始输入添加到输出,并编写自己的损失函数。这样你就可以做到
weight = y_true[...,0]
y_true = y_true[...,1:]
我也很想听到更好的答案:)
关于python - Keras 中的逐像素加权损失函数 - TensorFlow 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61225857/