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)
添加回答
舉報