單一母體比例檢定

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}}$ $\rightarrow$ 在 $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$ 估計母體標準差
    • 參數估計的不確定性 $\uparrow$
  • 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 中的假設檢定

一起來練習吧!

Python 中的假設檢定

Preparing Video For Download...