การทดสอบสมมติฐานด้วย Python
James Chapman
Curriculum Manager, DataCamp
$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})} $$
$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}}}$
$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}}}}}$
$H_{0}$: สัดส่วนผู้ใช้ Stack Overflow ที่อายุต่ำกว่าสามสิบปี $=0.5$
$H_{A}$: สัดส่วนผู้ใช้ Stack Overflow ที่อายุต่ำกว่าสามสิบปี $\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
p_hat = (stack_overflow['age_cat'] == 'Under 30').mean()
0.5356037151702786
p_0 = 0.50
n = len(stack_overflow)
2261
$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
หางซ้าย ("น้อยกว่า"):
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