【问题标题】:What should be the output of the custom loss function in Keras?Keras 中自定义损失函数的输出应该是什么?
【发布时间】:2019-10-12 09:06:49
【问题描述】:
我正在尝试在 Keras 中构建自定义损失函数,但我对它的工作方式感到困惑。我正在批量训练网络,我不确定损失函数的输出应该是一个与批次相同维度的数组还是只是一个标量。
【问题讨论】:
标签:
python
tensorflow
keras
conv-neural-network
【解决方案1】:
损失通常会在小批量的所有维度上减少。如果您不应用缩减,它将被隐式执行(尝试删除custom_loss_function() 中的tf.reduce_mean 并仅返回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
【解决方案2】:
如文档keras loss 中所述,您可以传递一个函数,该函数为每个数据点返回一个标量并接受两个参数:y_true(真实标签)和 y_pred(预测)。
Keras 在批次内对样本执行平均值,因此输出应该只是一个标量。