第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

keras 中的自定義二元交叉熵?fù)p失,忽略沒有非零值的列

keras 中的自定義二元交叉熵?fù)p失,忽略沒有非零值的列

回首憶惘然 2022-06-02 15:26:32
我正在嘗試在標(biāo)簽可能非常稀疏的地方分割數(shù)據(jù)。因此,我只想計算至少具有一個非零值的列中的梯度。我已經(jīng)嘗試了一些方法,其中我應(yīng)用了一個額外的輸入,即這些非零列的掩碼,但鑒于所有必要的信息已經(jīng)包含在 中y_true,只查看y_true查找掩碼的方法肯定會更可取。如果我用 numpy 實現(xiàn)它,它可能看起來像這樣: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 圖像。如何將其“轉(zhuǎn)化”為可微分的 Keras 損失函數(shù)?
查看完整描述

1 回答

?
繁星點點滴滴

TA貢獻(xiàn)1803條經(jīng)驗 獲得超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

我不確定您的問題的確切維度規(guī)格,但損失必須評估為單個值 - 上面沒有,因為您正在傳遞多維預(yù)測和標(biāo)簽。要減少暗淡,請用 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

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


查看完整回答
反對 回復(fù) 2022-06-02
  • 1 回答
  • 0 關(guān)注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號