簡體   English   中英

Keras中自定義損失函數的輸出應該是什么?

[英]What should be the output of the custom loss function in Keras?

我正在嘗試在Keras中構建自定義損失函數,但是我對其功能的方式感到困惑。 我正在分批訓練網絡,我不確定損失函數的輸出是否應該是與批處理具有相同維數或僅是標量的數組。

如文檔keras loss中所述 ,您可以傳遞一個函數,該函數為每個數據點返回一個標量,並接受兩個參數:y_true(真標簽)和y_pred(預測)。

Keras對批次內的樣本執行均值,因此輸出應僅為單個標量。

損失通常會在微型批次的所有尺寸上減小。 如果你不申請降低它會被隱式執行(嘗試刪除tf.reduce_meancustom_loss_function()並返回剛剛res )。 例如:

import tensorflow as tf
import numpy as np

def custom_cross_entropy(y_true, y_pred):
    res = -y_true*tf.math.log(tf.nn.softmax(y_pred))
    return tf.reduce_mean(res, axis=None)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(2, activation=None))

model.compile(optimizer=tf.keras.optimizers.SGD(0.01),
              loss=[custom_cross_entropy],
              metrics=['accuracy'])

y_train = np.array([[1, 0], [0, 1]])
x_train = np.random.normal(size=(2, 2))

model.fit(x_train, y_train, epochs=2)

# Epoch 1/2
# 2/2 [==============================] - 0s 13ms/sample - loss: 0.2689 - accuracy: 1.0000
# Epoch 2/2
# 2/2 [==============================] - 0s 2ms/sample - loss: 0.2686 - accuracy: 1.0000

暫無
暫無

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

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