我正在为高度不平衡的分类问题实现 CNN,并且我想在张量流中实现自定义指标以使用“选择最佳模型”回调。
具体来说,我想实现平衡的准确度分数,这是每个类别的召回率的平均值(请参阅 sklearn 实现here https://scikit-learn.org/stable/modules/generated/sklearn.metrics.balanced_accuracy_score.html),有人知道该怎么做吗?
我面临着同样的问题,所以我实现了一个基于的自定义类SparseCategoricalAccuracy
:
class BalancedSparseCategoricalAccuracy(keras.metrics.SparseCategoricalAccuracy):
def __init__(self, name='balanced_sparse_categorical_accuracy', dtype=None):
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
y_flat = y_true
if y_true.shape.ndims == y_pred.shape.ndims:
y_flat = tf.squeeze(y_flat, axis=[-1])
y_true_int = tf.cast(y_flat, tf.int32)
cls_counts = tf.math.bincount(y_true_int)
cls_counts = tf.math.reciprocal_no_nan(tf.cast(cls_counts, self.dtype))
weight = tf.gather(cls_counts, y_true_int)
return super().update_state(y_true, y_pred, sample_weight=weight)
这个想法是将每个类别的权重设置为其大小成反比。
这段代码从 Autograph 中产生了一些警告,但我相信这些是 Autograph 错误,并且该指标似乎工作正常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)