Chi-square anpassningstest

Hypotestestning i Python

James Chapman

Curriculum Manager, DataCamp

Lila länkar

Hur känner du dig när du märker att du redan besökt den bästa resursen?

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
Hypotestestning i Python

Formulera hypoteserna

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}$: Urvalet matchar den hypotetiserade fördelningen

$H_{A}$: Urvalet matchar inte den hypotetiserade fördelningen

$\chi^{2}$ mäter hur mycket det observerade resultatet avviker från förväntningarna i varje grupp

alpha = 0.01
Hypotestestning i Python

Hypotetiserade antal per kategori

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
Hypotestestning i Python

Visualisera antal

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()
Hypotestestning i Python

Visualisera antal

Stapeldiagram över antal svar mot purple_link-svar, med observerade antal i rött och hypotetiserade antal i blått.

Hypotestestning i Python

Chi-square anpassningstest

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)
Hypotestestning i Python

Nu kör vi en övning!

Hypotestestning i Python

Preparing Video For Download...