在张量流中计算基尼指数
Computing Gini index in tensorflow
我正在尝试将基尼指数计算记为张量流成本函数。基尼系数为:
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 中执行此操作(例如,在 tf 中没有 argsort 可以作为微分函数的一部分,AFAIK)
您可以使用 tf.nn.top_k()
执行参数排序。这个函数 returns 一个元组,第二个元素是索引。它的顺序必须颠倒,因为顺序是降序的。
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
这是一个代码,您可以使用它来验证此函数 returns 与您的 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})))
我正在尝试将基尼指数计算记为张量流成本函数。基尼系数为: 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 中执行此操作(例如,在 tf 中没有 argsort 可以作为微分函数的一部分,AFAIK)
您可以使用 tf.nn.top_k()
执行参数排序。这个函数 returns 一个元组,第二个元素是索引。它的顺序必须颠倒,因为顺序是降序的。
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
这是一个代码,您可以使用它来验证此函数 returns 与您的 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})))