Python中的加权基尼系数 [英] Weighted Gini coefficient in Python

查看:516
本文介绍了Python中的加权基尼系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here's a simple implementation of the Gini coefficient in Python, from 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

如何将其调整为将权重数组作为第二矢量?这应该采用非整数的权重,因此不仅要用权重来破坏数组.

How can this be adjusted to take an array of weights as a second vector? This should take noninteger weights, so not just blow up the array by the weights.

示例:

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的计算可以替换为:

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()重复元素:

to check the result, gini2() use numpy.repeat() to repeat elements:

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

这篇关于Python中的加权基尼系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆