繁体   English   中英

Theil Index Python与R

[英]Theil Index Python vs R

我正在尝试在python和R中计算Theil索引,但是使用给定的函数,我得到了不同的答案。 这是我要使用的公式:

泰尔计算

使用R中的ineq包,我可以轻松获得Theil索引:

library(ineq)
x=c(26.1,16.1,15.5,15.4,14.8,14.7,13.7,12.1,11.7,11.6,11,10.8,10.8,7.5)
Theil(x)
0.04152699

此实现似乎很有意义,我可以查看提供的代码以查看正在发生的确切计算,并且它似乎遵循公式(当我得到零以取日志时,将其删除为零):

getAnywhere(Theil )
Out[24]:
A single object matching ‘Theil’ was found
It was found in the following places
  package:ineq
  namespace:ineq
with value

function (x, parameter = 0, na.rm = TRUE) 
{
    if (!na.rm && any(is.na(x))) 
        return(NA_real_)
    x <- as.numeric(na.omit(x))
    if (is.null(parameter)) 
        parameter <- 0
    if (parameter == 0) {
        x <- x[!(x == 0)]
        Th <- x/mean(x)
        Th <- sum(x * log(Th))
        Th <- Th/sum(x)
    }
    else {
        Th <- exp(mean(log(x)))/mean(x)
        Th <- -log(Th)
    }
    Th
}

但是,我看到以前在这里为python之前已经回答了这个问题。 代码在这里,但是由于某些原因答案不匹配:

def T(x):
    n = len(x)
    maximum_entropy = math.log(n)
    actual_entropy = H(x)
    redundancy = maximum_entropy - actual_entropy
    inequality = 1 - math.exp(-redundancy)
    return redundancy,inequality 

def Group_negentropy(x_i):
    if x_i == 0:
        return 0
    else:
        return x_i*math.log(x_i)

def H(x):
    n = len(x)
    entropy = 0.0
    summ = 0.0
    for x_i in x: # work on all x[i]
        summ += x_i
        group_negentropy = Group_negentropy(x_i)
        entropy += group_negentropy
    return -entropy
x=np.array([26.1,16.1,15.5,15.4,14.8,14.7,13.7,12.1,11.7,11.6,11,10.8,10.8,7.5])
T(x)
(512.62045438815949, 1.0)

这是不是在其他问题明确规定,但执行预计其输入进行归一化,使每个x_i是收入的比例 ,而不是实际的量。 (这就是为什么其他代码具有error_if_not_in_range01函数并在x_i不在0和1之间的情况下引发错误的原因。)

如果对x规范化,则将得到与R代码相同的结果:

>>> T(x/x.sum())
(0.041526988117662533, 0.0406765553418974)

(第一个值是R报告的值。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM