【问题标题】:Weighted Gini coefficient in PythonPython中的加权基尼系数
【发布时间】:2018-02-26 13:22:03
【问题描述】:

这是一个简单的 Python 基尼系数实现,来自https://stackoverflow.com/a/39513799/1840471

def gini(x):
    # Mean absolute difference.
    mad = np.abs(np.subtract.outer(x, x)).mean()
    # Relative mean absolute difference
    rmad = mad / np.mean(x)
    # Gini coefficient is half the relative mean absolute difference.
    return 0.5 * rmad

如何调整它以将权重数组作为第二个向量?这应该采用非整数权重,所以不要仅仅通过权重来炸毁数组。

例子:

gini([1, 2, 3])  # No weight: 0.22.
gini([1, 1, 1, 2, 2, 3])  # Manually weighted: 0.23.
gini([1, 2, 3], weight=[3, 2, 1])  # Should also give 0.23.

【问题讨论】:

  • 不幸的是,mad 行计算矩阵的平均值,因此不能在那里应用权重。我怀疑使用权重和 np.subtract.outer 结果的一些矩阵数学,加上计算 rmd 的正常加权平均值,会起到作用。
  • 这不太奏效,但接受的答案起到了作用。
  • 我们能避免输入的全对比较吗? .outer.subtract 应用于所有对,但对于不适合内存的非常大的输入,这可能会很昂贵。是否有不需要对输入进行排序的流式算法?
  • @MarsellusWallace 这个解决方案效率更高:stackoverflow.com/questions/48999542/…

标签: python numpy gini


【解决方案1】:

mad的计算可以替换为:

x = np.array([1, 2, 3, 6])
c = np.array([2, 3, 1, 2])

count = np.multiply.outer(c, c)
mad = np.abs(np.subtract.outer(x, x) * count).sum() / count.sum()

np.mean(x) 可以替换为:

np.average(x, weights=c)

这是完整的功能:

def gini(x, weights=None):
    if weights is None:
        weights = np.ones_like(x)
    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)
    return 0.5 * rmad

要检查结果,gini2() 使用 numpy.repeat() 重复元素:

def gini2(x, weights=None):
    if weights is None:
        weights = np.ones(x.shape[0], dtype=int)    
    x = np.repeat(x, weights)
    mad = np.abs(np.subtract.outer(x, x)).mean()
    rmad = mad / np.mean(x)
    return 0.5 * rmad

【讨论】:

猜你喜欢
  • 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
相关资源
最近更新 更多