Python 3.x tensorflow中基尼指数的计算
我试图把基尼指数的计算写成一个张量流成本函数。基尼指数为: 一个重要的解决方案是Python 3.x tensorflow中基尼指数的计算,python-3.x,numpy,tensorflow,gini,Python 3.x,Numpy,Tensorflow,Gini,我试图把基尼指数的计算写成一个张量流成本函数。基尼指数为: 一个重要的解决方案是 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中,
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)您可以使用执行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})))
好的,这看起来不错,但是当作为损失函数传递给NN时,它会为第行返回一个错误:-->14 n=int(实际的.get_-shape()[-1])错误:TypeError:_-int_u返回非int(type-NoneType)如果我只是运行一个会话,它确实会像预期的那样工作。我认为发生这种情况是因为
actual
的占位符\张量的形状是(无,)
,这意味着它没有预定义的长度,因此在构建图形时无法计算n
。在这种情况下,您可以做的是将n
(数组的长度)作为附加参数传递给函数,而不是计算它。好的,我无法解决这个问题(尝试给出默认值n,但这并不能解决它)。我再次针对这个特殊问题提出了一个新问题,感谢您在TF中写下函数!有一个可微排序运算符的实现,TF中也有一个最近的研究结果