我最近在嘗試實作自定義損失函式時遇到了這個問題。以下兩個損失函式產生完全相同的結果,即使在第二個損失函式回傳的結果中添加了一個大的隨機值,并且確保了 jupyter notebook 中的可重復性。任何想法為什么會這樣?
def customLoss1():
def binary_crossentropy1(y_true, y_pred):
bin_cross = tf.keras.losses.BinaryCrossentropy()
bce = K.mean(bin_cross(y_true, y_pred))
return bce
return binary_crossentropy1
def customLoss2():
def binary_crossentropy2(y_true, y_pred):
bin_cross = tf.keras.losses.BinaryCrossentropy()
bce = K.mean(bin_cross(y_true, y_pred)) tf.random.normal([], mean=0.0, stddev=10.0)
return bce
return binary_crossentropy2
uj5u.com熱心網友回復:
您的錯誤必須在其他地方,因為您發布的損失函式確實會產生不同的結果:
import tensorflow as tf
tf.random.set_seed(11)
def binary_crossentropy1(y_true, y_pred):
bin_cross = tf.keras.losses.BinaryCrossentropy(from_logits=True)
bce = tf.keras.backend.mean(bin_cross(y_true, y_pred))
return bce
def binary_crossentropy2(y_true, y_pred):
bin_cross = tf.keras.losses.BinaryCrossentropy(from_logits=True)
bce = tf.keras.backend.mean(bin_cross(y_true, y_pred)) tf.random.normal([], mean=0.0, stddev=10.0)
return bce
y_true = tf.constant([0, 1, 0, 0])
y_pred = tf.constant([-18.6, 0.51, 2.94, -12.8])
print(binary_crossentropy1(y_true, y_pred))
print(binary_crossentropy2(y_true, y_pred))
tf.Tensor(0.865458, shape=(), dtype=float32)
tf.Tensor(-14.364014, shape=(), dtype=float32)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/415554.html
標籤:
