泰尔指数Python与R

问题描述:

我想在python和R中计算泰尔指数,但用给定的函数,我得到不同的答案。下面是我想使用的公式:泰尔指数Python与R

Theil Calculation

R中使用ineq包,我可以轻松地获得泰尔指数:

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 here。该代码是在这里,但答案不匹配出于某种原因:

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所报告的内容)