การทดสอบ chi-square goodness of fit

การทดสอบสมมติฐานด้วย Python

James Chapman

Curriculum Manager, DataCamp

ลิงก์สีม่วง

รู้สึกอย่างไรเมื่อพบว่าเคยเข้าชมแหล่งข้อมูลอันดับต้นนั้นแล้ว?

purple_link_counts = stack_overflow['purple_link'].value_counts()
purple_link_counts = purple_link_counts.rename_axis('purple_link')\
                                       .reset_index(name='n')\
                                       .sort_values('purple_link')
         purple_link     n
2             Amused   368
3            Annoyed   263
0  Hello, old friend  1225
1        Indifferent   405
การทดสอบสมมติฐานด้วย Python

การกำหนดสมมติฐาน

hypothesized = pd.DataFrame({
  'purple_link': ['Amused', 'Annoyed', 'Hello, old friend', 'Indifferent'], 
  'prop': [1/6, 1/6, 1/2, 1/6]})
         purple_link      prop
0             Amused  0.166667
1            Annoyed  0.166667
2  Hello, old friend  0.500000
3        Indifferent  0.166667

$H_{0}$: ตัวอย่างสอดคล้องกับการกระจายที่ตั้งสมมติฐาน

$H_{A}$: ตัวอย่างไม่สอดคล้องกับการกระจายที่ตั้งสมมติฐาน

$\chi^{2}$ วัดความแตกต่างระหว่างผลที่สังเกตได้กับค่าที่คาดหวังในแต่ละกลุ่ม

alpha = 0.01
การทดสอบสมมติฐานด้วย Python

จำนวนที่ตั้งสมมติฐานแยกตามหมวดหมู่

n_total = len(stack_overflow)
hypothesized["n"] = hypothesized["prop"] * n_total
         purple_link      prop            n
0             Amused  0.166667   376.833333
1            Annoyed  0.166667   376.833333
2  Hello, old friend  0.500000  1130.500000
3        Indifferent  0.166667   376.833333
การทดสอบสมมติฐานด้วย Python

แสดงผลจำนวนด้วยกราฟ

import matplotlib.pyplot as plt

plt.bar(purple_link_counts['purple_link'], purple_link_counts['n'], 
        color='red', label='Observed')

plt.bar(hypothesized['purple_link'], hypothesized['n'], alpha=0.5, color='blue', label='Hypothesized') plt.legend() plt.show()
การทดสอบสมมติฐานด้วย Python

แสดงผลจำนวนด้วยกราฟ

กราฟแท่งแสดงจำนวนคำตอบเทียบกับคำตอบ purple_link โดยค่าที่สังเกตได้แสดงด้วยสีแดงและค่าที่ตั้งสมมติฐานแสดงด้วยสีน้ำเงิน

การทดสอบสมมติฐานด้วย Python

การทดสอบ chi-square goodness of fit

print(hypothesized)
         purple_link      prop            n
0             Amused  0.166667   376.833333
1            Annoyed  0.166667   376.833333
2  Hello, old friend  0.500000  1130.500000
3        Indifferent  0.166667   376.833333
from scipy.stats import chisquare
chisquare(f_obs=purple_link_counts['n'], f_exp=hypothesized['n'])
Power_divergenceResult(statistic=44.59840778416629, pvalue=1.1261810719413759e-09)
การทดสอบสมมติฐานด้วย Python

มาฝึกกันเถอะ!

การทดสอบสมมติฐานด้วย Python

Preparing Video For Download...