亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Keras 自定義損失函數中y_true的大小

Keras 自定義損失函數中y_true的大小

至尊寶的傳說 2022-08-25 15:42:45
我正在嘗試在Keras中為U-net編寫一個自定義損失函數,其目的不僅是計算預測圖像和真實圖像的均方誤差(MSE),還要計算其梯度的MSE。我不確定這是否正常,但是在我的自定義損失函數中,即使從以下鏈接中,我也期望y_true的大小與y_pred相同,并且在我的情況下,它應該具有以下大?。海╞atch_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 domaindef 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_lossmodel.compile(optimizer='adam', loss = keras_customized_loss(BATCH_SIZE), metrics=['MeanAbsoluteError'])
查看完整描述

1 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

None意味著它接受可變大小。

因此,您的自定義損失可以非常靈活。


實際大小自然是傳遞給 的數據批的大小。

如果您的數據具有形狀,則無需擔心。fit(samples, 128,256,3)


但是你的代碼中有很多不必要的東西,你可以:


def keras_customized_loss(lambda1 = 1.0, lambda2 = 0.05):

    def grad_x(image):

        return K.abs(image[:, 1:] - image[:, :-1])


    def grad_y(image):

        return K.abs(image[:, :, 1:] - image[:, :, :-1])


    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


查看完整回答
反對 回復 2022-08-25
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號