【问题标题】:Computing a multi-index sum in a Tensorflow loss function在 Tensorflow 损失函数中计算多指标和
【发布时间】:2017-07-12 10:14:19
【问题描述】:

我正在尝试使用等效于concordance index(c-index)的损失函数来优化神经网络。我想使用的损失函数是(链接中的乳胶方程)

{i=0}^N ∑{j=i}^N \sigma ( (y_i - y_j)(y'_i - y'_j ) )

其中 y' 是预测向量,y 是大小为 N 的批次中的标签向量,\sigma 是 sigmoid 函数。我希望能够在 TensorFlow 中实现这一点,但我找不到表达两个索引和的方法。

我尝试将方程重新排列为可以用 TensorFlow 和 Keras 原语表示的不同形式,但没有成功。我正在使用 Keras,因此 Keras 或 TensorFlow 实现都可以使用。

Python 代码是

from itertools import permutations, combinations
a = np.arange(4)
a = a*100

def loss_ci(y_true, y_pred):
summ = 0.
total=0
for i in range(len(y_true)):
    for j in range(i+1,len(y_true)):
        summ += 1/(1+np.exp(-(y_true[i]-y_true[j]) * (y_pred[i]-y_pred[j])))
        total+=1
return (summ)/total

print("y_true\t\ty_pred\t\tc-index\tloss")
for c in permutations(a,3):
for d in combinations(a,3):
    print(c, d, "\t{:.4f}".format(ci(c, d)), "\t{:.4f}".format(loss_ci(c, d)))

【问题讨论】:

    标签: python tensorflow neural-network keras


    【解决方案1】:

    可以使用张量流计算损失,如下代码所示:

    from itertools import permutations, combinations
    a = np.arange(4)
    a = a*100
    
    def loss_ci(y_true, y_pred):
    summ = 0.
    total=0
    for i in range(len(y_true)):
        for j in range(i+1,len(y_true)):
            summ += 1/(1+np.exp(-(y_true[i]-y_true[j]) * (y_pred[i]-y_pred[j])))
    
    
    return (summ)
    
    def tf_loss_ci(y_true, y_pred):
      Y = tf.constant(y_true)
      _Y = tf.constant(y_pred)
      S = tf.sigmoid(tf.multiply((Y[tf.newaxis,:]-Y[:,tf.newaxis]),(_Y[tf.newaxis,:]-_Y[:,tf.newaxis])))
      S = tf.reduce_sum(tf.matrix_set_diag(S,tf.zeros_like(Y))) / 2
      sess = tf.InteractiveSession()
      tf.global_variables_initializer().run()
      return S.eval()
    
    print("y_true\t\ty_pred\t\ttensorloss\tloss")
    for c in permutations(a,3):
      for d in combinations(a,3):
        print(c, d, "\t{:.4f}".format(tf_loss_ci(np.asarray(c, np.float32), np.array(d, np.float32))), "\t{:.4f}".format(loss_ci(c, d)))
    

    【讨论】:

    • 谢谢,但这并没有实现 sigmoid 函数。我已经编辑了问题以包含损失函数的 numpy 版本。 (除以总数不是必需的,但可以显示损失如何等同于 c-index。)
    • 我的错误..做出了改变
    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2018-07-06
    • 2018-01-09
    • 2023-02-26
    • 2016-05-21
    相关资源
    最近更新 更多