【问题标题】:Having trouble converting r chisquare goodness of fit test code to python equivalent无法将 r 卡方拟合优度测试代码转换为 python 等效项
【发布时间】:2018-08-28 16:01:21
【问题描述】:

UCLA 有这个很棒的统计测试网站

https://stats.idre.ucla.edu/r/whatstat/what-statistical-analysis-should-i-usestatistical-analyses-using-r/#1sampt

但代码都在 R 中。我正在尝试将代码转换为 Python 等价物,但对于卡方拟合优度等某些人来说,这不是一个简单的过程。这是 R 版本:

hsb2 <- within(read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv"), {
  race <- as.factor(race)
  schtyp <- as.factor(schtyp)
  prog <- as.factor(prog)
})
chisq.test(table(hsb2$race), p = c(10, 10, 10, 70)/100)

我的 Python 尝试是这样的:

import numpy as np
import pandas as pd
from scipy import stats

df = pd.read_csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv")
# convert to category
df["race"] = df["race"].astype("category")

t_race = pd.crosstab(df.race, columns = 'race')
p_tests = np.array((10, 10, 10, 70))
p_tests = ptests/100
# tried this
stats.chisquare(t_race, p_tests)
# and this
stats.chisquare(t_race.T, p_tests)

但是 stats.chisquare 的输出都没有接近 R 版本。任何人都可以引导我朝着正确的方向前进吗? TIA

【问题讨论】:

    标签: python r chi-squared


    【解决方案1】:

    chisq.test 采用概率向量; stats.chisquare 采用预期的频率 (docs)。

    > results = chisq.test(c(24, 11, 20, 145), p=c(0.1, 0.1, 0.1, 0.7))
    > results
    
        Chi-squared test for given probabilities
    
    data:  c(24, 11, 20, 145)
    X-squared = 5.028571429, df = 3, p-value = 0.169716919
    

    对比

    In [49]: obs = np.array([24, 11, 20, 145])
    
    In [50]: prob = np.array([0.1, 0.1, 0.1, 0.7])
    
    In [51]: stats.chisquare(obs, f_exp=obs.sum() * prob)
    Out[51]: Power_divergenceResult(statistic=5.0285714285714285, pvalue=0.16971691923343338)
    

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多