0

这是 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.
4

1 回答 1

4

的计算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
于 2018-02-26T05:14:25.547 回答