如何计算张量流中的归一化基尼系数

时间:2017-10-20 22:56:15

标签: python numpy tensorflow kaggle gini

我正在尝试计算张量流中的标准化Gini Coefficient,但我无法这样做。我有以下python代码同样在numpy执行但我想使用tensorflow实现它。如有任何想法,请帮忙。 我将具有张量形状(1,?)的实际和具有张量形状的pred(1,?)

Python代码:

def gini(actual, pred, cmpcol = 0, sortcol = 1):
     assert( len(actual) == len(pred) )
     all = np.asarray(np.c_[ actual, pred, np.arange(len(actual)) ], dtype=np.float)
     all = all[ np.lexsort((all[:,2], -1*all[:,1])) ]
     totalLosses = all[:,0].sum()
     giniSum = all[:,0].cumsum().sum() / totalLosses

     giniSum -= (len(actual) + 1) / 2.
     return giniSum / len(actual)

 def gini_normalized(a, p):
     return gini(a, p) / gini(a, a)

2 个答案:

答案 0 :(得分:0)

这是一个张量流版本(使用tf.nn.top_k代替np.lexsort进行排序)。

def gini_tf(actual, pred):
  assert (len(actual) == len(pred))
  n = int(actual.get_shape()[-1])
  indices = tf.reverse(tf.nn.top_k(pred, k=n)[1], axis=0)
  a_s = tf.gather(actual, indices)
  a_c = tf.cumsum(a_s)
  giniSum = tf.reduce_sum(a_c) / tf.reduce_sum(a_s)
  giniSum -= (n + 1) / 2.
  return giniSum / n

gini_normalized没有变化。顺便说一下,看起来你的版本忽略了cmpcolsortcol个参数。

答案 1 :(得分:0)

这是一个有效的解决方案。

def gini(actual, pred):
    n = tf.shape(actual)[1]
    indices = tf.reverse(tf.nn.top_k(pred, k=n)[1], axis=[1])[0]
    a_s = tf.gather(tf.transpose(actual), tf.transpose(indices))
    a_c = tf.cumsum(a_s)
    giniSum = tf.reduce_sum(a_c) / tf.reduce_sum(a_s)
    giniSum = tf.subtract(giniSum, tf.divide(tf.to_float(n + 1), tf.constant(2.)))
    return giniSum / tf.to_float(n)

def gini_normalized(a, p):
    return gini(a, p) / gini(a, a)