Tensorflow 2.0中的Cohen Kappa二次损失怎么办?

时间:2019-11-21 16:46:02

标签: 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

不再存在。有其他选择吗?

1 个答案:

答案 0 :(得分:1)

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)

并将值强制转换为浮点数:

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是熊猫数据帧