您可以使用 执行 argsorting tf.nn.top_k()
。这个函数返回一个元组,第二个元素是索引。它的顺序必须颠倒,因为顺序是降序的。
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})))