簡體   English   中英

稀疏分類交叉熵導致 NAN 丟失

[英]Sparse Categorical CrossEntropy causing NAN loss

所以,我一直在嘗試實現一些自定義損失,所以我想我會從實現 SCE 損失開始,而不使用內置的 TF object。 這是我為它寫的 function。

def custom_loss(y_true, y_pred):
    print(y_true, y_pred)
    return tf.cast(tf.math.multiply(tf.experimental.numpy.log2(y_pred[y_true[0]]), -1), dtype=tf.float32)

y_pred 是概率集合,y_true 是正確概率的索引。 這個設置應該根據我讀過的所有內容工作,但它會返回 NAN 丟失。

我檢查了訓練循環是否有問題,但它與內置損失完美配合。

有人能告訴我這段代碼有什么問題嗎?

您可以復制SparseCategoricalCrossentropy()損失 function 如下

import tensorflow as tf

def sparse_categorical_crossentropy(y_true, y_pred, clip=True):

    y_true = tf.convert_to_tensor(y_true, dtype=tf.int32)
    y_pred = tf.convert_to_tensor(y_pred, dtype=tf.float32)

    y_true = tf.one_hot(y_true, depth=y_pred.shape[1])

    if clip == True:
        y_pred = tf.clip_by_value(y_pred, 1e-7, 1 - 1e-7)

    return - tf.reduce_mean(tf.math.log(y_pred[y_true == 1]))

請注意, SparseCategoricalCrossentropy()損失 function 對預測概率應用了一個小的偏移量 ( 1e-7 ),以確保損失值始終是有限的,另請參見此問題

y_true = [1, 2]
y_pred = [[0.05, 0.95, 0.0], [0.1, 0.8, 0.1]]

print(tf.keras.losses.SparseCategoricalCrossentropy()(y_true, y_pred).numpy())
print(sparse_categorical_crossentropy(y_true, y_pred, clip=True).numpy())
print(sparse_categorical_crossentropy(y_true, y_pred, clip=False).numpy())
# 1.1769392
# 1.1769392
# 1.1769392

y_true = [1, 2]
y_pred = [[0.0, 1.0, 0.0], [0.0, 1.0, 0.0]]

print(tf.keras.losses.SparseCategoricalCrossentropy()(y_true, y_pred).numpy())
print(sparse_categorical_crossentropy(y_true, y_pred, clip=True).numpy())
print(sparse_categorical_crossentropy(y_true, y_pred, clip=False).numpy())
# 8.059048
# 8.059048
# inf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM