[英]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.