python - 如何在Tensorflow 2.0中进行Cohen Kappa二次损失?

标签 python python-3.x tensorflow machine-learning tensorflow2.0

我正在尝试根据以下内容创建损失函数:

How can I specify a loss function to be quadratic weighted kappa in Keras?

但是在tensorflow 2.0中:

tf.contrib.metrics.cohen_kappa

不再存在。有替代方案吗?

最佳答案

def kappa_loss(y_pred, y_true, y_pow=2, eps=1e-10, N=4, bsize=256, name='kappa'):
"""A continuous differentiable approximation of discrete kappa loss.
    Args:
        y_pred: 2D tensor or array, [batch_size, num_classes]
        y_true: 2D tensor or array,[batch_size, num_classes]
        y_pow: int,  e.g. y_pow=2
        N: typically num_classes of the model
        bsize: batch_size of the training or validation ops
        eps: a float, prevents divide by zero
        name: Optional scope/name for op_scope.
    Returns:
        A tensor with the kappa loss."""

with tf.name_scope(name):
    y_true = tf.cast(y_true,dtype='float')
    repeat_op = tf.cast(tf.tile(tf.reshape(tf.range(0, N), [N, 1]), [1, N]), dtype='float')
    repeat_op_sq = tf.square((repeat_op - tf.transpose(repeat_op)))
    weights = repeat_op_sq / tf.cast((N - 1) ** 2, dtype='float')

    pred_ = y_pred ** y_pow
    try:
        pred_norm = pred_ / (eps + tf.reshape(tf.reduce_sum(pred_, 1), [-1, 1]))
    except Exception:
        pred_norm = pred_ / (eps + tf.reshape(tf.reduce_sum(pred_, 1), [bsize, 1]))

    hist_rater_a = tf.reduce_sum(pred_norm, 0)
    hist_rater_b = tf.reduce_sum(y_true, 0)

    conf_mat = tf.matmul(tf.transpose(pred_norm), y_true)

    nom = tf.reduce_sum(weights * conf_mat)
    denom = tf.reduce_sum(weights * tf.matmul(
        tf.reshape(hist_rater_a, [N, 1]), tf.reshape(hist_rater_b, [1, N])) /
                          tf.cast(bsize, dtype='float'))

    return nom / (denom + eps)

并使用

 lossMetric = kappa_loss
 model.compile(optimizer=optimizer, loss=lossMetric, metrics=metricsToWatch)

并预先将值转换为 float :

tf.cast(nn_x_train.values, dtype='float')

我还使用了 numpy 验证版本:

def qwk3(a1, a2, max_rat=3):
    assert(len(a1) == len(a2))
    a1 = np.asarray(a1, dtype=int)
    a2 = np.asarray(a2, dtype=int)

    hist1 = np.zeros((max_rat + 1, ))
    hist2 = np.zeros((max_rat + 1, ))

    o = 0
    for k in range(a1.shape[0]):
        i, j = a1[k], a2[k]
        hist1[i] += 1
        hist2[j] += 1
        o +=  (i - j) * (i - j)

    e = 0
    for i in range(max_rat + 1):
        for j in range(max_rat + 1):
            e += hist1[i] * hist2[j] * (i - j) * (i - j)

    e = e / a1.shape[0]

    return sum(1 - o / e)/len(1 - o / e)

并使用

nn_y_valid=tf.cast(nn_y_train.values, dtype='float')
print(qwk3(nn_y_valid, trainPredict))

其中 nn_x_train 和 nn_y_train 是 pandas 数据帧

关于python - 如何在Tensorflow 2.0中进行Cohen Kappa二次损失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58979824/

相关文章:

python - Basemap能否绘制城市级别的详细海岸线?

python - 处理请求中的 ValueError 后没有值?

python - 无论如何强制 PyCharm 总是使用绝对导入?

python - Django 测试在测试数据库创建上浪费了太多时间

python - 为什么加载 pickle 对象比加载文件花费的时间长得多?

python - 如何更改A3C Tensorflow示例来玩Atari游戏?

python - CNN 中局部层和密集层的区别

python-3.x - cython可以用icc编译吗?

python - 如何从python中的父文件夹导入函数?

python - tensorflow2.0还有参数 'trainable'吗?