【问题标题】:More efficient weighted Gini coefficient in PythonPython中更有效的加权基尼系数
【发布时间】:2018-02-27 01:00:19
【问题描述】:

根据https://stackoverflow.com/a/48981834/1840471,这是 Python 中加权基尼系数的实现:

import numpy as np
def gini(x, weights=None):
    if weights is None:
        weights = np.ones_like(x)
    # Calculate mean absolute deviation in two steps, for weights.
    count = np.multiply.outer(weights, weights)
    mad = np.abs(np.subtract.outer(x, x) * count).sum() / count.sum()
    rmad = mad / np.average(x, weights=weights)
    # Gini equals half the relative mean absolute deviation.
    return 0.5 * rmad

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

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

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

【问题讨论】:

标签: python numpy variations weighted gini


【解决方案1】:

这是一个比您上面提供的版本快得多的版本,并且还为没有重量的情况使用了简化的公式,以便在这种情况下获得更快的结果。

def gini(x, w=None):
    # The rest of the code requires numpy arrays.
    x = np.asarray(x)
    if w is not None:
        w = np.asarray(w)
        sorted_indices = np.argsort(x)
        sorted_x = x[sorted_indices]
        sorted_w = w[sorted_indices]
        # Force float dtype to avoid overflows
        cumw = np.cumsum(sorted_w, dtype=float)
        cumxw = np.cumsum(sorted_x * sorted_w, dtype=float)
        return (np.sum(cumxw[1:] * cumw[:-1] - cumxw[:-1] * cumw[1:]) / 
                (cumxw[-1] * cumw[-1]))
    else:
        sorted_x = np.sort(x)
        n = len(x)
        cumx = np.cumsum(sorted_x, dtype=float)
        # The above formula, with all weights equal to 1 simplifies to:
        return (n + 1 - 2 * np.sum(cumx) / cumx[-1]) / n

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

>>> x = np.random.rand(1000000)
>>> w = np.random.rand(1000000)
>>> gini_max_ghenis(x, w)
0.33376310938610521
>>> gini(x, w)
0.33376310938610382

但是速度差别很大:

%timeit gini(x, w)
203 ms ± 3.68 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit gini_max_ghenis(x, w)
55.6 s ± 3.35 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

如果你从函数中删除 pandas 操作,它已经快得多了:

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

如果您想获得最后的性能下降,您可以使用 numba 或 cython,但这只会提高几个百分点,因为大部分时间都花在了排序上。

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

编辑:gini_max_ghenis 是 Max Ghenis 回答中使用的代码

【讨论】:

  • gini_slowgini_slow2 是什么?
  • gini_slow 是上面 Max Ghenis 发布的版本。 gini_slow2 是避免所有基于 pandas 的操作的函数(即不创建系列,因此使用普通索引而不是 .iloc)
  • @A-B-B 我刚刚采用了一个已知的算法(顺便匹配了 Max Ghenis 给出的代码)并生成了它的向量化 numpy 版本。我使用它的数据从来没有负面的,所以我从来没有做过研究。快速浏览一下 Max answer 中链接的页面,我会说很可能确实如此,但我没有时间或意愿去实际检查。如果你这样做,请评论!
  • 您知道是否存在根本不同的基尼计算方法?您的函数与 R 的 reldist::gini() 的输出匹配,但与 DescTools::Gini 非常不同。我想知道同行评审的代码怎么会发生这种情况。例如。 [1,1,1,1,1000] 对您来说是 0.796,但对 DescTools 来说是 0.995。也许这些方法只在小的-n 空间中发散。
  • @geotheory 我认为这是因为 DescTools 的版本默认是无偏见的(乘以 n/(n-1)。0.796*5/4 = 0.995
【解决方案2】:

here改编StatsGini R函数:

import numpy as np
import pandas as pd

def gini(x, w=None):
    # Array indexing requires reset indexes.
    x = pd.Series(x).reset_index(drop=True)
    if w is None:
        w = np.ones_like(x)
    w = pd.Series(w).reset_index(drop=True)
    n = x.size
    wxsum = sum(w * x)
    wsum = sum(w)
    sxw = np.argsort(x)
    sx = x[sxw] * w[sxw]
    sw = w[sxw]
    pxi = np.cumsum(sx) / wxsum
    pci = np.cumsum(sw) / wsum
    g = 0.0
    for i in np.arange(1, n):
        g = g + pxi.iloc[i] * pci.iloc[i - 1] - pci.iloc[i] * pxi.iloc[i - 1]
    return g

这适用于大向量,至少高达 10M 行:

n = 1e7
gini(np.random.rand(n), np.random.rand(n))  # Takes ~15s.

它也产生与问题中提供的函数相同的结果,例如在这个例子中给出 0.2553:

gini(np.array([3, 1, 6, 2, 1]), np.array([4, 2, 2, 10, 1]))

【讨论】:

  • @RadioControlled 请提交一个新问题,以获得没有 pandas 的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 2023-04-02
  • 1970-01-01
  • 2018-07-11
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多