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

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

keras 中的自定義二元交叉熵損失,忽略沒有非零值的列

keras 中的自定義二元交叉熵損失,忽略沒有非零值的列

回首憶惘然 2022-06-02 15:26:32
我正在嘗試在標簽可能非常稀疏的地方分割數據。因此,我只想計算至少具有一個非零值的列中的梯度。我已經嘗試了一些方法,其中我應用了一個額外的輸入,即這些非零列的掩碼,但鑒于所有必要的信息已經包含在 中y_true,只查看y_true查找掩碼的方法肯定會更可取。如果我用 numpy 實現它,它可能看起來像這樣:def loss(y_true, y_pred):     indices = np.where(np.sum(y_true, axis=1) > 0)         return binary_crossentropy(y_true[indices], y_pred[indices])y_truey_pred在這個例子中是矢量化的 2D 圖像。如何將其“轉化”為可微分的 Keras 損失函數?
查看完整描述

1 回答

?
繁星點點滴滴

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

使用tf- 兼容的操作,通過tf和keras.backend:


import tensorflow as tf

import keras.backend as K

from keras.losses import binary_crossentropy


def custom_loss(y_true, y_pred):

    indices = K.squeeze(tf.where(K.sum(y_true, axis=1) > 0))

    y_true_sparse = K.cast(K.gather(y_true, indices), dtype='float32')

    y_pred_sparse = K.cast(K.gather(y_pred, indices), dtype='float32')

    return binary_crossentropy(y_true_sparse, y_pred_sparse) # returns a tensor

我不確定您的問題的確切維度規格,但損失必須評估為單個值 - 上面沒有,因為您正在傳遞多維預測和標簽。要減少暗淡,請用 eg 包裹上面的 return K.mean。例子:


y_true = np.random.randint(0,2,(10,2))

y_pred = np.abs(np.random.randn(10,2))

y_pred /= np.max(y_pred) # scale between 0 and 1


print(K.get_value(custom_loss(y_true, y_pred))) # get_value evaluates returned tensor

print(K.get_value(K.mean(custom_loss(y_true, y_pred))

>> [1.1489482  1.2705883  0.76229745  5.101402  3.1309896] # sparse; 5 / 10 results

>> 2.28284 # single value, as required

(最后,請注意,這種稀疏性會通過從總標簽/預測計數中排除全零列來偏置損失;如果不希望,您可以通過K.sumand K.shapeor進行平均K.size)


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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