2017-07-12 44 views
0

我正在試驗使用相當於concordance index(c指數)的損失函數來優化神經網絡。損耗函數我想用是(在鏈路膠乳方程)在Tensorflow損失函數中計算多指標總和

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

其中y」爲預測和y的矢量是標籤的在批處理的大小爲N的向量,和\西格瑪是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))) 

回答

0

損失可以用張量流作爲顯示在下面的代碼來計算:

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))) 
+0

謝謝,但這並不執行乙狀結腸機能的研究。我已經編輯了這個問題來包含損失函數的numpy版本。 (除以總數是沒有必要的,但是顯示了損失如何等同於C指數。) –

+0

我的錯誤..做了修改 –

+0

這很有效,非常感謝 –