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