Skip to content

Hypothesis Testing in Python

Run the hidden code cell below to import the data used in this course.

# Import pandas
import pandas as pd

# Import the course datasets 
republican_votes = pd.read_feather('datasets/repub_votes_potus_08_12.feather')
democrat_votes = pd.read_feather('datasets/dem_votes_potus_12_16.feather')
shipments = pd.read_feather('datasets/late_shipments.feather')
stackoverflow = pd.read_feather("datasets/stack_overflow.feather")

Take Notes

Add notes about the concepts you've learned and code cells with code you want to keep.

Add your notes here

# Add your code snippets here

Hypotyses testing on python

Для того что бы протестировать гипотезу, что среднее какого-то генеральной совокупности например равняется 0.06 Мы должны взять реально среднее и рассчитать его затем рассчитать стандартную ошибку среднего, взяв бустрап выборку и рассчитав стандартную ошибку, затем рассчитать Z score вычесть из реального среднего предполагаемое и разделить разность на стандартную ошибку

# Hypothesize that the proportion is 6%
late_prop_hyp = 0.06

# Calculate the standard error
std_error = np.std(late_shipments_boot_distn, ddof=1)

# Find z-score of late_prop_samp
z_score = (late_prop_samp - late_prop_hyp) / std_error

# Print z_score
print(z_score)

Далее мы формируем гипотезы, например Г0- Отличий нет Г1- Реальное больше шести

Правосторонний тест так как мы узнаем больше ли? передаем на вход скор для нормального распределения и так как считаем для правого хвоста вычитаем из одного

# Calculate the z-score of late_prop_samp
z_score = (late_prop_samp-late_prop_hyp)/std_error

# Calculate the p-value
p_value = 1-norm.cdf(z_score, loc=0, scale=1)
                 
# Print the p-value
print(p_value) 

Переходим к T-тесту

Например есть предположение что посылки которые доставлялись весят меньше, чем те которые опаздывали Когда нам нужно рассчитать действительно ли разница является статистически значимой для генеральной совокупности или это просто в выборке так случилось

Нам нужно рассчитать t-test Для этого нужны средние по выборке, разделенные по признаку опоздали они или нет среднее веса посылки опоздавшей среднее веса посылки не опаздавшей стандартные отклонения с разделением по той же схеме и размеры выборок по той же схеме

While trying to determine why some shipments are late, you may wonder if the weight of the shipments that were on time is less than the weight of the shipments that were late. The late_shipments dataset has been split into a "yes" group, where late == "Yes" and a "no" group where late == "No". The weight of the shipment is given in the weight_kilograms variable.

The sample means for the two groups are available as xbar_no and xbar_yes. The sample standard deviations are s_no and s_yes. The sample sizes are n_no and n_yes. numpy is also loaded as np

# Calculate the numerator of the test statistic
numerator = xbar_yes - xbar_no

# Calculate the denominator of the test statistic
denominator = np.sqrt((s_no**2)/n_no + (s_yes**2)/n_yes)

# Calculate the test statistic
t_stat = numerator/denominator

# Print the test statistic
print(t_stat)
# Calculate the degrees of freedom
degrees_of_freedom = n_no + n_yes - 2

# Calculate the p-value from the test stat
p_value = t.cdf(t_stat, df=degrees_of_freedom)

# Print the p_value
print(p_value)

Парный т тест предназначен когда мы сравниваем например результаты выборов за разные года парный потому что одна и та же демография или с одной и той же выборкой до и после какого-то воздействия

Нужно рассчитать разницу между значениями и отсюда рассчитать т статистику по формуле

среднего разделить на корень стандартной ошибки в квадрате деленной на количество наблюдений с степенями свободы минус 1

# Calculate the differences from 2012 to 2016
sample_dem_data['diff'] = sample_dem_data['dem_percent_12'] - sample_dem_data['dem_percent_16']

# Find the mean of the diff column
xbar_diff = sample_dem_data['diff'].mean()

# Find the standard deviation of the diff column
s_diff = sample_dem_data['diff'].std()

import pingouin

test_results = pingouin.ttest(x=sample_dem_data['diff'], 
                              y=0, 
                              alternative="two-sided")

paired = pingouin.ttest(x=sample_dem_data['dem_percent_12'], 
               y=sample_dem_data['dem_percent_16'], 
               alternative="two-sided", paired=True)

Anova test

Для сравнения нескольких переменных одновременно

Например у нас есть датасет с посылками и мы хотим сказать есть ли отличие от способов доставки по цене упаковки

Гипотезы 0: Pack prices for every category of shipment mode are the same.

1: Pack prices for some categories of shipment mode are different.