简体   繁体   English

来自重采样方法与 scipy.stats.chi2_contigency 的卡方检验 P 值

[英]Chi-square test P-value from resampled method vs scipy.stats.chi2_contigency

This question references to book "O'Relly Practical Statistics for Data Scientists 2nd Edition" chapter 3, session Chi-Square Test.本题参考“O'Relly Practical Statistics for Data Scientist 2nd Edition”第3章,会话卡方检验。

The book provides an example of one Chi-square test case, where it assumes a website with three different headlines that run by 1000 visitors.这本书提供了一个卡方测试用例的例子,它假设一个网站有三个不同的标题,有 1000 名访问者。 The result shows the # of clicks from each headline.结果显示了每个标题的点击次数。

The Observed data is the following:观察到的数据如下:

Headline   A    B    C
Click      14   8    12
No-click   986  992  988

The expected value is calculated in the following:预期值计算如下:

Headline   A        B        C
Click      11.13    11.13    11.13
No-click   988.67   988.67   988.67

The Pearson residual is defined as: Pearson 残差定义为: 皮尔逊残差

Where the table is now:桌子现在在哪里:

Headline   A        B        C
Click      0.792    -0.990   0.198
No-click   -0.085   0.106   -0.021

The Chi-square statistic is the sum of the squared Pearson residuals:卡方统计量是 Pearson 残差平方的总和: 在此处输入图片说明 . . Which is 1.666这是 1.666

So far so good.到现在为止还挺好。 Now here comes the resampling part:现在是重采样部分:

1. Assuming a box of 34 ones and 2966 zeros
2. Shuffle, and take three samples of 1000 and count how many ones(Clicks)
3. Find the squared differences between the shuffled counts and expected counts then sum them.
4. Repeat steps 2 to 3, a few thousand times.
5. The P-value is how often does the resampled sum of squared deviations exceed the observed.

The resampling python test code is provided by the book as following: (Can be downloaded from https://github.com/gedeck/practical-statistics-for-data-scientists/tree/master/python/code )本书提供的重采样python测试代码如下:(可从https://github.com/gedeck/practical-statistics-for-data-scientists/tree/master/python/code下载)

## Practical Statistics for Data Scientists (Python)
## Chapter 3. Statistial Experiments and Significance Testing
# > (c) 2019 Peter C. Bruce, Andrew Bruce, Peter Gedeck

# Import required Python packages.

from pathlib import Path
import random

import pandas as pd
import numpy as np

from scipy import stats
import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.stats import power

import matplotlib.pylab as plt

DATA = Path('.').resolve().parents[1] / 'data'

# Define paths to data sets. If you don't keep your data in the same directory as the code, adapt the path names.

CLICK_RATE_CSV = DATA / 'click_rates.csv'

...

## Chi-Square Test
### Chi-Square Test: A Resampling Approach

# Table 3-4
click_rate = pd.read_csv(CLICK_RATE_CSV)
clicks = click_rate.pivot(index='Click', columns='Headline', values='Rate')
print(clicks)

# Table 3-5
row_average = clicks.mean(axis=1)
pd.DataFrame({
    'Headline A': row_average,
    'Headline B': row_average,
    'Headline C': row_average,
})

# Resampling approach
box = [1] * 34
box.extend([0] * 2966)
random.shuffle(box)

def chi2(observed, expected):
    pearson_residuals = []
    for row, expect in zip(observed, expected):
        pearson_residuals.append([(observe - expect) ** 2 / expect
                                  for observe in row])
    # return sum of squares
    return np.sum(pearson_residuals)

expected_clicks = 34 / 3
expected_noclicks = 1000 - expected_clicks
expected = [34 / 3, 1000 - 34 / 3]
chi2observed = chi2(clicks.values, expected)

def perm_fun(box):
    sample_clicks = [sum(random.sample(box, 1000)),
                     sum(random.sample(box, 1000)),
                     sum(random.sample(box, 1000))]
    sample_noclicks = [1000 - n for n in sample_clicks]
    return chi2([sample_clicks, sample_noclicks], expected)

perm_chi2 = [perm_fun(box) for _ in range(2000)]

resampled_p_value = sum(perm_chi2 > chi2observed) / len(perm_chi2)

print(f'Observed chi2: {chi2observed:.4f}')
print(f'Resampled p-value: {resampled_p_value:.4f}')

chisq, pvalue, df, expected = stats.chi2_contingency(clicks)
print(f'Observed chi2: {chi2observed:.4f}')
print(f'p-value: {pvalue:.4f}')

Now, i ran the perm_fun(box) for 2,000 times and obtained a resampled P-value of 0.4775.现在,我运行 perm_fun(box) 2,000 次并获得了 0.4775 的重采样 P 值。 However, if I ran perm_fun(box) for 10,000 times, and 100,000 times, I was able to obtain a resampled P-value of 0.84 both times.但是,如果我运行 perm_fun(box) 10,000 次和 100,000 次,两次都能够获得 0.84 的重采样 P 值。 It seems to me the P-value should be around 0.84.在我看来,P 值应该在 0.84 左右。 Why is the stats.chi2_contigency showing a such smaller numbers?为什么 stats.chi2_contigency 显示的数字如此之小?

The result I get for running 2000 times is:我运行 2000 次的结果是:

Observed chi2: 1.6659
Resampled p-value: 0.8300
Observed chi2: 1.6659
p-value: 0.4348

And if I were to run it 10,000 times, the result is:如果我运行它 10,000 次,结果是:

Observed chi2: 1.6659
Resampled p-value: 0.8386
Observed chi2: 1.6659
p-value: 0.4348

software version:软件版本:

pandas.__version__:         0.25.1
numpy.__version__:          1.16.5
scipy.__version__:          1.3.1
statsmodels.__version__:    0.10.1
sys.version_info:           3.7.4

I ran your code trying 2000, 10000, and 100000 loops, and all three times I got close to .47.我运行了您的代码,尝试了 2000、10000 和 100000 次循环,并且所有 3 次都接近 0.47。 I did, however, get an error at this line that I had to fix:但是,我确实在这一行遇到了一个我必须修复的错误:

resampled_p_value = sum(perm_chi2 > chi2observed) / len(perm_chi2)

Here perm_chi2 is a list and chi2observed is a float, so I wonder how this code ever ran for you (perhaps whatever you did to fix it was the source of the error).这里perm_chi2是一个列表, chi2observed是一个浮点数,所以我想知道这段代码是如何为你运行的(也许你为修复它所做的一切都是错误的根源)。 In any case, changing it to the intended无论如何,将其更改为预期的

resampled_p_value = sum([1*(x > chi2observed) for x in perm_chi2]) / len(perm_chi2)

allowed me to run it and get close to .47.允许我运行它并接近 0.47。

Make sure that when you change the number of iterations, you do so only by changing the 2000, none of the other numbers.确保在更改迭代次数时,只更改 2000,而不更改其他任何数字。

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

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