Tags: #◇CSMODEL #◇Inference for Categorical Data #◇Computer Science #◇Data Science #◇Statistical Modeling #◇Python #◇Machine Learning
Module 09: Inference for Categorical Data
◇Key Concepts
1. Introduction to Categorical Data Inference
In statistical modeling and data science, categorical data consists of variables representing qualitative categories rather than numerical measurements (e.g., survey agreement, political affiliation, health status, race, or success/failure outcomes).
While numerical data is analyzed using inference on means () and standard deviations (), categorical data requires inference based on proportions () and frequencies/counts ().
Categorical inference is categorized based on the number of variables and categories involved:
- One Proportion: Testing or estimating the population proportion for a single binary variable ().
- Two Proportions: Comparing population proportions across two independent groups ().
- Goodness-of-Fit (Single Variable, Categories): Comparing observed sample frequencies across categories to a theoretical or historical population distribution.
- Test of Independence (Two Variables, Contingency Table): Evaluating whether two categorical variables are independent or statistically associated.
2. Inference for a Single Proportion (One-Proportion z-Test)
Concept & Hypotheses
The One-Proportion z-Test assesses whether a population proportion equals a hypothesized baseline proportion .
Null Hypothesis (): (The true population proportion is equal to the hypothesized value ). Alternative Hypothesis ():
Two-tailed:
One-tailed: or
Sample Proportion & Standard Error
Given a sample of size with observed successes:
Under , the sampling distribution of is centered at with standard error:
Test Statistic
Confidence Interval for a Proportion
To construct a confidence interval for , we use the sample proportion for standard error estimation:
where is the critical value from the standard normal distribution (e.g., for confidence).
Relationship Between and Margin of Error (ME)
The Margin of Error varies depending on : Maximum ME: Achieved when . (Worst-case scenario; used when planning sample size without prior knowledge of ). Minimum ME: Achieved when approaches or .
Conditions for One-Proportion z-Test & CI
- Independence: The sample observations must be independent.
Random sampling / random assignment.
Condition: If sampling without replacement, sample size of the total population. - Success-Failure Condition:
For Hypothesis Testing: Expected successes AND expected failures .
For Confidence Intervals: Observed successes AND observed failures .
3. Inference for Two Proportions (Two-Proportion z-Test)
Concept & Hypotheses
The Two-Proportion z-Test compares the proportions of two independent populations ( and ).
Null Hypothesis (): (There is no difference between the two population proportions). Alternative Hypothesis (): (or , ).
Pooled Proportion ()
Under , we assume . The best estimate of this common proportion is obtained by pooling the successes and sample sizes from both groups:
Standard Error & Test Statistic
The pooled standard error for the difference under is:
The z-test statistic is:
Conditions for Two-Proportion z-Test
- Independence: Within each group and between the two groups (independent random samples).
- Success-Failure Condition: Expected successes and failures in BOTH groups under must be at least 10:
4. Chi-Square () Goodness-of-Fit Test
Concept & Hypotheses
The Chi-Square Goodness-of-Fit Test determines whether an observed categorical frequency distribution across categories () matches an expected theoretical or baseline population distribution.
Null Hypothesis (): The sample distribution follows the specified population distribution (there is no difference between observed and expected proportions). Alternative Hypothesis (): The sample distribution does NOT follow the specified population distribution (at least one category proportion differs).
Expected Frequencies ()
Given total sample size and hypothesized category probabilities :
Note that .
Test Statistic
The Chi-Square statistic measures the aggregate normalized squared deviation of observed frequencies () from expected frequencies ():
always. If for all , (perfect fit). Larger values of indicate greater discrepancy between sample data and .
Degrees of Freedom ()
where is the number of categories/bins.
Conditions for Goodness-of-Fit Test
- Independence: Each observation in the sample must be independent of all other observations.
- Expected Cell Counts Condition: EVERY expected cell count must be at least 5 ( for all ).
Crucial Note: This condition applies to expected counts (), NOT observed counts ().
5. Chi-Square () Test of Independence
Concept & Hypotheses
The Chi-Square Test of Independence evaluates whether two categorical variables measured on the same sample are independent of each other or statistically associated.
Null Hypothesis (): Variable A and Variable B are independent (the outcome of one variable does not depend on the outcome of the other). Alternative Hypothesis (): Variable A and Variable B are dependent / associated (the distribution of one variable differs across levels of the other).
Contingency Table ()
Observations are summarized in a two-way contingency table with rows (categories of Variable A) and columns (categories of Variable B).
Expected Frequencies ()
Under the null hypothesis of independence, . The expected frequency for cell is:
Test Statistic & Degrees of Freedom
Conditions for Test of Independence
- Independence: Sample observations are randomly selected and independent of one another.
- Expected Cell Counts Condition: EVERY expected cell count .
6. Interpreting Chi-Square Test Results
Right-Tailed Nature: Because discrepancies are squared, all non-zero terms are positive. Chi-Square tests are inherently one-sided (right-tailed). p-value: . Decision Rule:
If (e.g., ): Reject . Conclude there is statistically significant evidence of a difference or relationship.
If : Fail to reject (or accept ). The sample data does not provide sufficient evidence to rule out chance variation.
◇Python Snippets
1. Contingency Tables with pd.crosstab()
Creates a frequency cross-tabulation of two categorical series from a pandas DataFrame.
import pandas as pd
# Load dataset
cdc_df = pd.read_csv('cdcpartial.csv')
# Create a contingency table of exercise history vs general health status
counts = pd.crosstab(cdc_df['exerany'], cdc_df['genhlth'])
# Format into a clean DataFrame with custom row labels
table = pd.DataFrame([counts.loc[0], counts.loc[1]], index=['no exercise', 'exercise'])
print(table)
2. Chi-Square Test of Independence with scipy.stats.chi2_contingency()
Calculates the statistic, p-value, degrees of freedom, and expected frequencies for a contingency table.
from scipy.stats import chi2_contingency
# Perform Chi-Square Test of Independence
# Note: set correction=False to get standard Pearson chi-square without Yates' continuity correction
chi2_stat, p_val, dof, expected = chi2_contingency(table, correction=False)
print(f"Chi-Square Statistic : {chi2_stat:.4f}")
print(f"p-value : {p_val:.4e}")
print(f"Degrees of Freedom : {dof}")
print("Expected Frequencies :\n", expected)
# Statistical Decision
alpha = 0.05
if p_val < alpha:
print("Reject H0: The two categorical variables are dependent.")
else:
print("Fail to reject H0: The two categorical variables are independent.")
3. Chi-Square Goodness-of-Fit Test with scipy.stats.chisquare()
Tests whether observed category counts differ significantly from expected theoretical frequencies.
from scipy.stats import chisquare
# Example: Juror race distribution vs expected counts based on voter registration
observed = [205, 26, 25, 19] # Observed counts: White, Black, Hispanic, Other
expected = [198.0, 19.25, 33.0, 24.75] # Expected counts: Total (275) * voter %
# Perform Goodness-of-Fit test
gof_result = chisquare(f_obs=observed, f_exp=expected)
print(f"Goodness-of-Fit Chi2 Stat : {gof_result.statistic:.4f}")
print(f"p-value : {gof_result.pvalue:.4f}")
4. Proportion z-Tests with statsmodels.stats.proportion.proportions_ztest()
Handles both 1-proportion z-tests and 2-proportion z-tests.
from statsmodels.stats.proportion import proportions_ztest
# --- ONE-PROPORTION z-TEST ---
# H0: p = 0.10 vs H1: p != 0.10
# Observed: 140 atheists in sample of 1000 respondents
count_1 = 140
nobs_1 = 1000
value_0 = 0.10
z_stat_1, p_val_1 = proportions_ztest(count=count_1, nobs=nobs_1, value=value_0, alternative='two-sided')
print(f"1-Prop z-statistic: {z_stat_1:.4f}, p-value: {p_val_1:.4f}")
# --- TWO-PROPORTION z-TEST ---
# Group 1 (Smokers): 150 had condition out of 500
# Group 2 (Non-Smokers): 180 had condition out of 700
counts_2 = [150, 180]
nobs_2 = [500, 700]
z_stat_2, p_val_2 = proportions_ztest(count=counts_2, nobs=nobs_2, alternative='two-sided')
print(f"2-Prop z-statistic: {z_stat_2:.4f}, p-value: {p_val_2:.4f}")
5. Computing Sample Proportion Confidence Intervals & Margin of Error
Calculates the point estimate, standard error, margin of error, and confidence interval bounds in Python.
import numpy as np
from scipy.stats import norm
# Sample statistics from Atheism survey (US 2012 sample)
n = 1002
atheist_count = 50
atheist_prop = atheist_count / n
# 95% Confidence Interval Calculation
confidence_level = 0.95
z_crit = norm.ppf(1 - (1 - confidence_level) / 2) # approx 1.96
# Standard Error and Margin of Error
se = np.sqrt(atheist_prop * (1 - atheist_prop) / n)
margin_of_error = z_crit * se
minimum_value = atheist_prop - margin_of_error
maximum_value = atheist_prop + margin_of_error
print(f"Sample Proportion : {atheist_prop * 100:.4f}%")
print(f"Margin of Error : {margin_of_error * 100:.4f}%")
print(f"95% CI : ({minimum_value * 100:.4f}%, {maximum_value * 100:.4f}%)")
◇Formulas & Key Equations
| Formula / Metric | Mathematical Expression | Key Context / Notes |
|---|---|---|
| Sample Proportion | Ratio of observed successes to sample size . | |
| 1-Prop Hypothesis Test SE | Uses hypothesized value under . | |
| 1-Prop Confidence Interval SE | Uses sample proportion . | |
| 1-Prop z-Test Statistic | Tests . | |
| Proportion Margin of Error | Maximized when . | |
| Pooled Proportion (2-Prop) | Combines successes under . | |
| 2-Prop z-Test Statistic | Compares two independent proportions. | |
| Chi-Square Expected Cell Count (GOF) | = sample size, = theoretical probability. | |
| Chi-Square Expected Cell Count (Independence) | Calculated for each cell in an table. | |
| Chi-Square Statistic () | Aggregate normalized squared deviation. | |
| Degrees of Freedom (GOF) | = number of categories. | |
| Degrees of Freedom (Independence) | = number of rows, = number of columns. |
◇Common Exam Traps
-
Checking on Observed Counts instead of Expected Counts:
Wrong: Rejecting a Chi-Square test because an observed cell count is .
Correct: The condition requires EXPECTED counts (). It is completely fine if observed counts are small or even , as long as all . -
Standard Error Formula: vs Confusion:
Wrong: Using in the SE denominator when calculating the 1-proportion z-test statistic.
Correct:
For Hypothesis Testing (-test), use : .
For Confidence Intervals (), use : . -
Degrees of Freedom Miscalculation in Contingency Tables:
Wrong: Setting for a Test of Independence.
Correct: For a Test of Independence, . For Goodness-of-Fit, . -
Yates' Continuity Correction in Python (
chi2_contingency):
Wrong: Expectingscipy.stats.chi2_contingency(table)to equal hand calculations when analyzing a table without checking parameters.
Correct: By default, SciPy applies Yates' continuity correction (correction=True) for tables, which shrinks . Setcorrection=Falseto reproduce exact Pearson hand calculations on exams. -
Assuming Chi-Square Tests are Two-Tailed:
Wrong: Splitting into two tails () for a Chi-Square p-value.
Correct: Chi-Square tests are always right-tailed because squared terms enforce . Any deviation from pushes further into the upper tail. -
Maximum Margin of Error Misinterpretation:
Wrong: Thinking Margin of Error is highest when sample proportion is close to or .
Correct: Margin of Error is maximized at and shrinks as or .
◇Practice Questions
Q1. A Computer Science department wants to test if students are equally distributed across 4 elective tracks: Data Science (DS), Software Technology (ST), Network & Security (NS), and Interactive Media (IM). In a random sample of students, the observed counts are: DS: ST: NS: IM:
Calculate the Chi-Square statistic and state the degrees of freedom . At a significance level of (critical value ), what is the statistical conclusion? A) ; Fail to reject (distribution is equal). B) ; Reject (distribution is not equal). C) ; Reject (distribution is not equal). D) ; Reject (distribution is not equal).
Q2. A researcher surveys 200 university students to test whether major choice (Major A vs Major B) is independent of obtaining an internship (Interned vs Did Not Intern). The observed contingency table is:
| Major | Interned | Did Not Intern | Total |
|---|---|---|---|
| Major A | 100 | ||
| Major B | 100 | ||
| Total | 100 | 100 | 200 |
What is the expected count for Major A students who Interned under , and what is the Pearson Chi-Square test statistic ? A) B) C) D)
Q3. An e-commerce platform tests two website layouts (Layout 1 and Layout 2) to determine if there is a difference in conversion proportions. Layout 1: conversions out of visitors (). Layout 2: conversions out of visitors ().
What is the pooled sample proportion and the calculated z-test statistic? A) B) C) D)
Q4. Inspect the following Python code snippet:
import pandas as pd
from scipy.stats import chi2_contingency
df_table = pd.DataFrame({
'Pass': [85, 65],
'Fail': [15, 35]
}, index=['Course_X', 'Course_Y'])
chi2, p_val, dof, expected = chi2_contingency(df_table, correction=False)
print(f"dof={dof}, exp_CourseX_Fail={expected[0,1]:.1f}")
What is the exact output printed by this script? A) dof=1, exp_CourseX_Fail=25.0 B) dof=2, exp_CourseX_Fail=25.0 C) dof=1, exp_CourseX_Fail=15.0 D) dof=4, exp_CourseX_Fail=50.0
Q5. A data analyst runs the following Python code to test if a coin is biased towards heads ( vs ):
from statsmodels.stats.proportion import proportions_ztest
# Observed 60 heads in 100 tosses
count = 60
nobs = 100
value = 0.50
z_stat, p_val = proportions_ztest(count=count, nobs=nobs, value=value, alternative='larger')
print(f"z={z_stat:.2f}")
Given that under , , what exact value is printed for z? A) z=1.00 B) z=1.96 C) z=2.00 D) z=4.00
Q6. A statistical consultant is conducting a Chi-Square Test of Independence on a contingency table. Which of the following statements regarding test assumptions and degrees of freedom is TRUE? A) The degrees of freedom for this test is . B) Every observed cell count must be greater than or equal to 5. C) Every expected cell count must be greater than or equal to 5, and . D) The Chi-Square test statistic can be negative if observed counts are less than expected counts.
Answer Key
Q1: B — ; Reject
Step-by-step Solution:
Total sample . Under equal distribution (), expected probability for each of the tracks is .
Expected frequency for each track: .
Degrees of freedom: .
Chi-Square components:
.
Since calculated , we reject .
Q2: B —
Step-by-step Solution:
Row total for Major A = . Column total for Interned = . Grand Total .
Expected count for cell (Major A, Interned):
Similarly, all four expected counts equal .
Chi-Square Statistic:
Q3: A —
Step-by-step Solution:
Pooled proportion:
Sample proportions: , .
Difference in sample proportions: .
.
Q4: A — dof=1, exp_CourseX_Fail=25.0
Step-by-step Solution:
df_table dimensions: 2 rows (Course_X, Course_Y), 2 columns (Pass, Fail).
Degrees of freedom: .
Row Total for Course_X = . Column Total for Fail = . Grand Total .
Expected count for Course_X Fail (index [0,1]):
Python prints: dof=1, exp_CourseX_Fail=25.0.
Q5: C — z=2.00
Step-by-step Solution:
Sample proportion: .
Hypothesized proportion under : .
Standard Error under : .
.
Q6: C — Every expected cell count , and .
Step-by-step Solution:
For a Test of Independence on an table, degrees of freedom .
The sample size condition requires expected cell counts , not observed cell counts .
Chi-Square statistics cannot be negative because all terms .
◇References & Navigation
- Previous Topic: ◇Inference for Means
- Next Topic: ◇Bayesian Inference
- Related Notes: ◇Foundations for Inference, ◇Inference for Means
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
Which of the following is true about categorical data compared to numerical data in statistical inference?
In a One-Proportion z-Test, what is the correct formula for the standard error under the null hypothesis?
When planning sample sizes for a confidence interval, under which condition is the Margin of Error maximized?
Which condition must be met to use the normal approximation in a One-Proportion z-Test?
What is the purpose of calculating a pooled proportion () in a Two-Proportion z-Test?
In a Chi-Square Goodness-of-Fit Test, what does the null hypothesis () generally state?
How are the degrees of freedom calculated for a Chi-Square Test of Independence on an contingency table?
What is the "Expected Cell Counts Condition" for a valid Chi-Square test?
Why are Chi-Square tests inherently one-sided (right-tailed)?
When using Python's scipy.stats.chi2_contingency function on a table, why might the results differ from manual Pearson calculations?