我有以下数据:

array([[33, 250, 196, 136, 32],
       [55, 293, 190,  71, 13]])


我可以从stats.chi2_contingency(data)获取p值。

是否有与此R对象-data.chisq$residuals类似的东西,以获取Pearson的残差和标准化的残差?

最佳答案

如果您不介意依赖性,则statsmodels具有用于contingency table calculations的模块。例如,

In [2]: import numpy as np

In [3]: import statsmodels.api as sm

In [4]: F = np.array([[33, 250, 196, 136, 32], [55, 293, 190,  71, 13]])

In [5]: table = sm.stats.Table(F)

In [6]: table.resid_pearson  # Pearson's residuals
Out[6]:
array([[-1.77162519, -1.61362277, -0.05718356,  2.96508777,  1.89079393],
       [ 1.80687785,  1.64573143,  0.05832142, -3.02408853, -1.92841787]])

In [7]: table.standardized_resids  # Standardized residuals
Out[7]:
array([[-2.62309082, -3.0471942 , -0.09791681,  4.6295814 ,  2.74991911],
       [ 2.62309082,  3.0471942 ,  0.09791681, -4.6295814 , -2.74991911]])




如果不想使用statsmodels,则可以使用scipy.stats.chi2_contingency的结果在几行中执行这些计算。这是定义这些残差函数的简短模块。它们采用观察到的频率和期望的频率(由chi2_contingency返回)。请注意,虽然chi2_contingency和以下residuals函数适用于n维数组,但此处实现的stdres仅适用于2D数组。

from __future__ import division

import numpy as np
from scipy.stats.contingency import margins


def residuals(observed, expected):
    return (observed - expected) / np.sqrt(expected)

def stdres(observed, expected):
    n = observed.sum()
    rsum, csum = margins(observed)
    # With integers, the calculation
    #     csum * rsum * (n - rsum) * (n - csum)
    # might overflow, so convert rsum and csum to floating point.
    rsum = rsum.astype(np.float64)
    csum = csum.astype(np.float64)
    v = csum * rsum * (n - rsum) * (n - csum) / n**3
    return (observed - expected) / np.sqrt(v)


利用您的数据,我们得到:

>>> F = np.array([[33, 250, 196, 136, 32], [55, 293, 190, 71, 13]])

>>> chi2, p, dof, expected = chi2_contingency(F)

>>> residuals(F, expected)
array([[-1.77162519, -1.61362277, -0.05718356,  2.96508777,  1.89079393],
       [ 1.80687785,  1.64573143,  0.05832142, -3.02408853, -1.92841787]])

>>> stdres(F, expected)
array([[-2.62309082, -3.0471942 , -0.09791681,  4.6295814 ,  2.74991911],
       [ 2.62309082,  3.0471942 ,  0.09791681, -4.6295814 , -2.74991911]])


这是R中的计算结果,用于比较:

> F <- as.table(rbind(c(33, 250, 196, 136, 32), c(55, 293, 190, 71, 13)))

> result <- chisq.test(F)

> result$residuals
            A           B           C           D           E
A -1.77162519 -1.61362277 -0.05718356  2.96508777  1.89079393
B  1.80687785  1.64573143  0.05832142 -3.02408853 -1.92841787

> result$stdres
            A           B           C           D           E
A -2.62309082 -3.04719420 -0.09791681  4.62958140  2.74991911
B  2.62309082  3.04719420  0.09791681 -4.62958140 -2.74991911

关于python - python中的R data.chisq $ residuals等价于什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20453729/

10-11 20:44