单样本比例检验

Python 假设检验

James Chapman

Curriculum Manager, DataCamp

第 1 章回顾

  • 某个未知总体比例的主张是否合理?

 

  1. 自助法分布估计样本统计量的标准误
  2. 计算标准化检验统计量
  3. 计算 p 值
  4. 判断哪个假设更合理

 

  • 现在,在不使用自助法分布的情况下计算检验统计量
Python 假设检验

比例的标准化检验统计量

$p$:总体比例(未知总体参数)

$\hat{p}$:样本比例(样本统计量)

$p_{0}$:假设的总体比例

$$ z = \frac{\hat{p} - \text{mean}(\hat{p})}{\text{SE}(\hat{p})} = \frac{\hat{p} - p}{\text{SE}(\hat{p})} $$

在 $H_{0}$ 成立下,$p = p_{0}$,因此

$$ z = \dfrac{\hat{p} - p_{0}}{\text{SE}(\hat{p})} $$

Python 假设检验

简化标准误计算

$SE_{\hat{p}} = \sqrt{\dfrac{p_{0}*(1-p_{0})}{n}}$ → 在 $H_0$ 下,$SE_{\hat{p}}$ 取决于假设的 $p_0$ 和样本量 $n$

在 $H_{0}$ 成立下,

$z = \dfrac{\hat{p} - p_{0}}{\sqrt{\dfrac{p_{0}*(1-p_{0})}{n}}}$

  • 仅使用样本信息($\hat{p}$ 与 $n$)和假设参数($p_{0}$)
Python 假设检验

为何用 z 而非 t?

$t = \dfrac{(\bar{x}_{\text{child}} - \bar{x}_{\text{adult}})}{\sqrt{\dfrac{s_{\text{child}}^2}{n_{\text{child}}} + \dfrac{s_{\text{adult}}^2}{n_{\text{adult}}}}}$

  • $s$ 由 $\bar{x}$ 计算
    • $\bar{x}$ 估计总体均值
    • $s$ 估计总体标准差
    • 我们对参数估计的不确定性 ↑
  • t 分布——尾部比正态更胖
  • $\hat{p}$ 只出现在分子中,因此使用 z 分数即可
Python 假设检验

Stack Overflow 年龄类别

$H_{0}$:Stack Overflow 中 30 岁以下的比例 $=0.5$

$H_{A}$:Stack Overflow 中 30 岁以下的比例 $\neq0.5$

alpha = 0.01
stack_overflow['age_cat'].value_counts(normalize=True)
Under 30       0.535604
At least 30    0.464396
Name: age_cat, dtype: float64
Python 假设检验

z 的变量

p_hat = (stack_overflow['age_cat'] == 'Under 30').mean()
0.5356037151702786
p_0 = 0.50
n = len(stack_overflow)
2261
Python 假设检验

计算 z 分数

$z = \dfrac{\hat{p} - p_{0}}{\sqrt{\dfrac{p_{0}*(1-p_{0})}{n}}}$

import numpy as np
numerator = p_hat - p_0
denominator = np.sqrt(p_0 * (1 - p_0) / n)
z_score = numerator / denominator
3.385911440783663
Python 假设检验

计算 p 值

正态分布的CDF。小于 -2 的部分为红色,大于 2 的部分为绿色。 左尾("小于"):

from scipy.stats import norm
p_value = norm.cdf(z_score)

右尾("大于"):

p_value = 1 - norm.cdf(z_score)

双尾("不等于"):

p_value = norm.cdf(-z_score) + 
  1 - norm.cdf(z_score)
p_value = 2 * (1 - norm.cdf(z_score))
0.0007094227368100725
p_value <= alpha
True
Python 假设检验

Passons à la pratique !

Python 假设检验

Preparing Video For Download...