假设我们有预测的输出向量:
y_pred = [1, 0, 0, 1]
和实际的输出值:
y_true = [0, 1, 0, 0]
我想建立以下差异向量y_pred-y_true:
y_diff = [1, -1, 0, 1]
计算其中的1的数量并将其乘以一个常数。这应该是我的自定义损失函数的结果。目标是更加重视某种错误(在这种情况下,如果预测值为0而真实值为1,我希望损失更大)。
这是我的实现尝试:
def custom_loss_function(y_true, y_pred):
# if it was 1 and you wrote 0, error is very very big
y_diff = tf.math.subtract(y_true, y_pred)
def fn(elem):
if elem == 1:
return 10
elif elem == -1:
return 1
else:
return 0
return tf.reduce_sum(tf.map_fn(fn, y_diff))
问题在于,我的损失函数将不会是“可微的”。我认为这是我收到错误的原因:
ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
关于如何实现自定义损失函数(在当前任务中,根据某些条件会产生更大(或更小)损失)的任何想法?
您的问题是矛盾的。您说要,y_pred - y_true
但要y_true - y_pred
在代码中计算。不过,您可以使用以下内容。
def custom_loss_function(y_true, y_pred):
# if it was 1 and you wrote 0, error is very very big
y_diff = y_true - y_pred
mul_mask = tf.cast(tf.math.equal(y_diff, 1.0), tf.float32)*9.0 + 1
y_diff = tf.math.sqrt((y_diff * mul_mask)**2)
return tf.reduce_sum(y_diff)
PS:我希望您有充分的理由使用此自定义损失功能。由于您可以class_weights
在进行操作时仅使用参数进行加权model.fit()
,因此,如果您只想按类加权,则无需自己实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句