简体   繁体   English

使用自定义损失 function 时 model.fit() 出错

[英]Error in model.fit() when using custom loss function

I have defined a custom loss function for my model.我为我的 model 定义了自定义损失 function。

def get_loss(y_hat, y):
loss = tf.keras.losses.BinaryCrossentropy(y_hat,y)  # cross entropy (but no logits)


y_hat = tf.math.sigmoid(y_hat)

tp = tf.math.reduce_sum(tf.multiply(y_hat, y),[1,2])
fn = tf.math.reduce_sum((y - tf.multiply(y_hat, y)),[1,2])
fp = tf.math.reduce_sum((y_hat -tf.multiply(y_hat,y)),[1,2])
loss = loss - ((2 * tp) / tf.math.reduce_sum((2 * tp + fp + fn + 1e-10)))  # fscore

return loss

When fitting my model to my training data I get following error:将我的 model 拟合到我的训练数据时,出现以下错误:

TypeError: Expected float32, got <tensorflow.python.keras.losses.BinaryCrossentropy object at 0x7feca46d0d30> of type 'BinaryCrossentropy' instead.

How can I fix this?我怎样才能解决这个问题? I already tried to use:我已经尝试使用:

loss=tf.int32(tf.keras.losses.BinaryCrossentropy(y_hat,y)

but this spits out another error and seems to not be the solution I need但这吐出了另一个错误,似乎不是我需要的解决方案

You need to call the instantiated object, rather than passing the input as arguments.您需要调用实例化的 object,而不是将输入作为 arguments 传递。 As such:像这样:

loss = tf.keras.losses.BinaryCrossentropy()(y_hat,y)

Notice the extra set of parentheses.注意额外的一组括号。 Or, do it like this:或者,这样做:

loss = tf.keras.losses.binary_crossentropy(y_hat, y)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 自定义损失 function 在 model.fit() 中输出 nan - custom loss function outputs nan in model.fit() 在Keras中调用model.fit时无法从损失函数运行打印语句 - unable to run print statements from loss function when calling model.fit in Keras In Tensorflow.keras 2.0, when a model has multiple outputs, how to define a flexible loss function for model.fit()? - In Tensorflow.keras 2.0, when a model has multiple outputs, how to define a flexible loss function for model.fit()? 为什么model.fit()使用categorical_crossentropy损失函数通过tf.train.AdamOptimizer引发ValueError? - Why does model.fit() raise ValueError with tf.train.AdamOptimizer using categorical_crossentropy loss function? 当尝试使用 model.fit() 训练 tensorflow model 时,`ResourceExhaustedError: Graph execution error` - `ResourceExhaustedError: Graph execution error` when trying to train tensorflow model using model.fit() TensorFlow错误模型.fit() - TensorFlow error model.fit() Keras:修复使用 model.fit 时出现的“IndexError: list index out of range”错误 - Keras: fix "IndexError: list index out of range" error when using model.fit 在 Tensorflow 中执行 model.fit 时输入错误 - Type Error when model.fit is executed in Tensorflow 调用 model.fit() 时出现 Colab TPU 错误:UnimplementedError - Colab TPU Error when calling model.fit() : UnimplementedError Tensorflow Keras:运行model.fit时出现尺寸/形状错误 - Tensorflow Keras: Dimension/Shape Error when running model.fit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM