我正在尝试在Keras中为U-net编写一个自定义损失函数,其目的不仅是计算预测图像和真实图像的均方误差(MSE),还要计算其梯度的MSE。
我不确定这是否正常,但是在我的自定义损失函数中,即使从以下链接中,我也期望y_true的大小与y_pred相同,并且在我的情况下,它应该具有以下大小:(batch_size,128,256, 3).y_true
我已经列出了我为自定义损失函数编写的代码,如果有人能给出任何建议,我将不胜感激。
import tensorflow.keras.backend as K
# Encouraging the predicted image to match the label not only in image domain, but also in gradient domain
def keras_customized_loss(batch_size, lambda1 = 1.0, lambda2 = 0.05):
def grad_x(image):
out = K.zeros((batch_size,)+image.shape[1:4])
out = K.abs(image[0:batch_size, 1:, :, :] - image[0:batch_size, :-1, :, :])
return out
def grad_y(image):
out = K.zeros((batch_size,)+image.shape[1:4])
out = K.abs(image[0:batch_size, :, 1:, :] - image[0:batch_size, :, :-1, :])
return out
#OBS: Now y_true has size: (None, None, None, None), figure out how to solve it
def compute_loss(y_true, y_pred):
pred_grad_x = grad_x(y_pred)
pred_grad_y = grad_y(y_pred)
true_grad_x = grad_x(y_true)
true_grad_y = grad_y(y_true)
loss1 = K.mean(K.square(y_pred-y_true))
loss2 = K.mean(K.square(pred_grad_x-true_grad_x))
loss3 = K.mean(K.square(pred_grad_y-true_grad_y))
return (lambda1*loss1+lambda2*loss2+lambda2*loss3)
return compute_loss
model.compile(optimizer='adam', loss = keras_customized_loss(BATCH_SIZE), metrics=['MeanAbsoluteError'])
慕森王
相关分类