计算张量流中的基尼指数

时间:2017-10-10 02:26:50

标签: python-3.x numpy tensorflow gini

我正在尝试将基尼指数计算写为张量流成本函数。基尼指数是: https://en.wikipedia.org/wiki/Gini_coefficient

numpy解决方案

def ginic(actual, pred):
    n = len(actual)
    a_s = actual[np.argsort(pred)]
    a_c = a_s.cumsum()
    giniSum = a_c.sum() / a_s.sum() - (n + 1) / 2.0
    return giniSum / n

有人可以帮我弄清楚如何在tf中做到这一点(例如,如果没有argsort可以成为差异化功能的一部分,AFAIK)

1 个答案:

答案 0 :(得分:2)

您可以使用tf.nn.top_k()执行argsorting。此函数返回一个元组,第二个元素是索引。由于订单正在下降,因此必须撤销其订单。

def ginicTF(actual:tf.Tensor,pred:tf.Tensor):
    n = int(actual.get_shape()[-1])
    inds =  tf.reverse(tf.nn.top_k(pred,n)[1],axis=[0]) # this is the equivalent of np.argsort
    a_s = tf.gather(actual,inds) # this is the equivalent of numpy indexing
    a_c = tf.cumsum(a_s)
    giniSum = tf.reduce_sum(a_c)/tf.reduce_sum(a_s) - (n+1)/2.0
    return giniSum / n

以下是一个代码,可用于验证此函数返回与numpy函数ginic相同的数值:

sess = tf.InteractiveSession()
ac = tf.placeholder(shape=(50,),dtype=tf.float32)
pr = tf.placeholder(shape=(50,),dtype=tf.float32)
actual  = np.random.normal(size=(50,))
pred  = np.random.normal(size=(50,))
print('numpy version: {:.4f}'.format(ginic(actual,pred)))
print('tensorflow version: {:.4f}'.format(ginicTF(ac,pr).eval(feed_dict={ac:actual,pr:pred})))