Python中更有效的加权基尼系数

前端之家收集整理的这篇文章主要介绍了Python中更有效的加权基尼系数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
根据 https://stackoverflow.com/a/48981834/1840471,这是Python中加权基尼系数的实现:
  1. import numpy as np
  2. def gini(x,weights=None):
  3. if weights is None:
  4. weights = np.ones_like(x)
  5. # Calculate mean absolute deviation in two steps,for weights.
  6. count = np.multiply.outer(weights,weights)
  7. mad = np.abs(np.subtract.outer(x,x) * count).sum() / count.sum()
  8. rmad = mad / np.average(x,weights=weights)
  9. # Gini equals half the relative mean absolute deviation.
  10. return 0.5 * rmad

这很干净,适用于中型阵列,但正如其最初的建议(https://stackoverflow.com/a/39513799/1840471)所警告的那样是O(n2).在我的计算机上,这意味着它在大约20k行之后中断:

  1. n = 20000 # Works,30000 fails.
  2. gini(np.random.rand(n),np.random.rand(n))

可以调整它以适用于更大的数据集吗?我的行是~150k行.

解决方法

这是一个比上面提供的版本快得多的版本,并且在没有重量的情况下使用简化的公式来获得更快的结果.
  1. def gini(x,w=None):
  2. # The rest of the code requires numpy arrays.
  3. x = np.asarray(x)
  4. if w is not None:
  5. w = np.asarray(w)
  6. sorted_indices = np.argsort(x)
  7. sorted_x = x[sorted_indices]
  8. sorted_w = w[sorted_indices]
  9. # Force float dtype to avoid overflows
  10. cumw = np.cumsum(sorted_w,dtype=float)
  11. cumxw = np.cumsum(sorted_x * sorted_w,dtype=float)
  12. return (np.sum(cumxw[1:] * cumw[:-1] - cumxw[:-1] * cumw[1:]) /
  13. (cumxw[-1] * cumw[-1]))
  14. else:
  15. sorted_x = np.sort(x)
  16. n = len(x)
  17. cumx = np.cumsum(sorted_x,dtype=float)
  18. # The above formula,with all weights equal to 1 simplifies to:
  19. return (n + 1 - 2 * np.sum(cumx) / cumx[-1]) / n

这里有一些测试代码来检查我们得到(大多数)相同的结果:

  1. >>> x = np.random.rand(1000000)
  2. >>> w = np.random.rand(1000000)
  3. >>> gini_slow(x,w)
  4. 0.33376310938610521
  5. >>> gini(x,w)
  6. 0.33376310938610382

但速度差异很大:

  1. %timeit gini(x,w)
  2. 203 ms ± 3.68 ms per loop (mean ± std. dev. of 7 runs,1 loop each)
  3.  
  4. %timeit gini_slow(x,w)
  5. 55.6 s ± 3.35 s per loop (mean ± std. dev. of 7 runs,1 loop each)

如果从函数删除pandas ops,它已经快得多:

  1. %timeit gini_slow2(x,w)
  2. 1.62 s ± 75 ms per loop (mean ± std. dev. of 7 runs,1 loop each)

如果你想获得最后一滴性能,你可以使用numba或cython,但这只会获得几个百分点,因为大部分时间都花在排序上.

  1. %timeit ind = np.argsort(x); sx = x[ind]; sw = w[ind]
  2. 180 ms ± 4.82 ms per loop (mean ± std. dev. of 7 runs,10 loops each)

猜你在找的Python相关文章