汉明损失计算我们的预测错误的标签数量并对其进行归一化处理。
HammingLoss 作为指标的标准实现依赖于对错误预测的计数,大致如下:(在 TF 上)
count_non_zero = tf.math.count_nonzero(actuals - predictions)
return tf.reduce_mean(count_non_zero / actuals.get_shape()[-1])
将汉明损失实现为实际损失需要它是可微分的,由于 tf.math.count_nonzero
而不是这种情况。
另一种(和近似的)方法是以这种方式计算非零标签,但不幸的是,NN 似乎没有改进。
def hamming_loss(y_true, y_pred):
y_true = tf.convert_to_tensor(y_true, name="y_true")
y_pred = tf.convert_to_tensor(y_pred, name="y_pred")
diff = tf.cast(tf.math.abs(y_true - y_pred), dtype=tf.float32)
#Counting non-zeros in a differentiable way
epsilon = K.epsilon()
nonzero = tf.reduce_mean(tf.math.abs( diff / (tf.math.abs(diff) + epsilon)))
return tf.reduce_mean(nonzero / K.int_shape(y_pred)[-1])
最后,TensorFlow 的汉明损失的正确实现是什么?
最佳答案
您的网络不会收敛,因为:
diff / (tf.math.abs(diff) + epsilon)
产生一个 0 , 1
向量,它杀死了 0 和 1 上的梯度
关于python - TensorFlow 的可微分汉明损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257047/