【发布时间】:2020-10-11 11:06:12
【问题描述】:
我正在尝试通过这个公式实现自定义损失:
这是为我的模型使用真正的自定义损失函数的第一步。数据集是 Keras Cifar10。实现似乎正确,但我收到此错误:
OperatorNotAllowedInGraphError: using a tf.Tensoras a Pythonbool is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
def custom_loss(y_true, y_pred):
# −(????log(????)+(1−????)log(1−????))
return tf.sqrt(tf.divide(tf.reduce_sum(tf.pow(tf.subtract(y_true, y_pred),2.0)),tf.cast(tf.size(y_true), tf.float32)))
我什至尝试将我的 train_labels(从 unit8 转换为 float32),但这没有帮助。 任何帮助将不胜感激。
我的模型是一个简单的 5 层 CNN 模型:
model = keras.models.Sequential([keras.layers.Conv2D(filters= 3,kernel_size=(3,3),activation= keras.activations.relu, input_shape= (32,32,3)),
keras.layers.MaxPool2D(pool_size= (2,2)),
keras.layers.Conv2D(filters= 3,kernel_size=(3,3),activation= keras.activations.relu),
keras.layers.MaxPool2D(pool_size= (2,2)),
keras.layers.Flatten(),
keras.layers.Dense(units= 64, activation= keras.activations.relu),
keras.layers.Dense(units= 10, activation= keras.activations.softmax)])
model.compile(loss= classification_loss(train_labels,model.layers[-1].output),optimizer= keras.optimizers.Adam(), metrics=['accuracy'])
model.fit(x= train_images, y= train_labels,epochs=10)
【问题讨论】:
-
您在寻找经典的 MSE 吗? en.wikipedia.org/wiki/Mean_squared_error
-
@MarcoCerliani 对不起我的错误。我所有的问题是实现一个 custom_loss,即使是简单的预定义的。公式就是这种损失的一个例子。
标签: keras tensorflow2.0 loss-function