Showing posts with label Chi-square test. Show all posts
Showing posts with label Chi-square test. Show all posts

Tuesday, November 12, 2024

Chi-Square Test for Categorical Data






Chi-Square Test, Degrees of Freedom, Normalization vs Standardization & Tobit Regression Explained

Chi-Square Test, Degrees of Freedom, Normalization vs Standardization & Tobit Regression Explained

Statistics forms the mathematical backbone of modern data science, machine learning, econometrics, and research analysis. Among the most important statistical concepts are the Chi-Square Test, Degrees of Freedom, Normalization, Standardization, and advanced regression methods like the Tobit Model.

Understanding these concepts allows analysts to evaluate relationships between variables, preprocess datasets correctly, test hypotheses, and build more reliable predictive systems.

Key Learning Goals:
  • Understand contingency tables
  • Learn Chi-Square hypothesis testing
  • Calculate expected frequencies
  • Interpret p-values and significance
  • Understand normalization and standardization
  • Learn Wald and Likelihood Ratio tests in Tobit regression
  • Implement everything in Python


1. Introduction to Chi-Square Testing

The Chi-Square test is one of the most widely used statistical methods for categorical data analysis.

It helps answer questions like:

  • Do boys and girls prefer different colors?
  • Is customer preference related to age group?
  • Is there an association between smoking and disease?
  • Are observed outcomes significantly different from expected outcomes?

The Chi-Square test compares:

  • Observed frequencies
  • Expected frequencies

If the difference between them is large enough, the relationship is considered statistically significant.


2. Contingency Tables

A contingency table organizes categorical data into rows and columns.

Green Pink Blue Total
Boys O1 O2 O3 B
Girls O4 O5 O6 G
Total T1 T2 T3 N

This table allows researchers to evaluate whether gender and color preference are associated.


3. Expected Frequencies

Expected frequencies represent the values we would expect if there were no relationship between variables.

\[ E_{ij} = \frac{(Row\ Total_i)(Column\ Total_j)}{Grand\ Total} \]

Example

\[ E_{Boys,Green} = \frac{B \times T1}{N} \]

If observed values differ significantly from expected values, the variables may be associated.


4. Chi-Square Statistic Formula

\[ \chi^2 = \sum \frac{(O_{ij} - E_{ij})^2}{E_{ij}} \]

Where:

  • \(O_{ij}\) = Observed frequency
  • \(E_{ij}\) = Expected frequency

The Chi-Square statistic measures deviation between observed and expected frequencies.

Larger Chi-Square values indicate stronger evidence against the null hypothesis.

5. Degrees of Freedom

Degrees of freedom determine which Chi-Square distribution should be used.

Formula for Independence Test

\[ df = (Rows - 1)(Columns - 1) \]

Example

\[ df = (2-1)(3-1)=2 \]

Goodness-of-Fit Formula

\[ df = Categories - 1 \]

6. Hypothesis Testing

Null Hypothesis

Variables are independent.

Alternative Hypothesis

Variables are associated.

Decision rules:

  • p-value < 0.05 → reject null hypothesis
  • p-value > 0.05 → fail to reject null hypothesis

7. Interpreting Results

Condition Interpretation
Large Chi-Square Strong evidence of association
Small Chi-Square Weak evidence of association
p-value < 0.05 Statistically significant
p-value > 0.05 Not statistically significant

8. Goodness-of-Fit Test

This test evaluates whether observed frequencies match a theoretical distribution.

Example

Suppose a die is rolled 60 times. Expected frequency:

\[ E = \frac{60}{6}=10 \]

Chi-Square determines whether deviations from 10 are due to chance.


9. Test of Independence

This test evaluates whether two categorical variables are related.

Examples:

  • Gender vs color preference
  • Education vs income level
  • Smoking vs lung disease

10. Normalization

Normalization rescales values into a fixed range, usually:

\[ [0,1] \]

Formula

\[ X' = \frac{X - X_{min}}{X_{max}-X_{min}} \]

Normalization is useful when:

  • Features have different scales
  • Neural networks are used
  • Distance-based models are applied

11. Standardization

Standardization transforms data to:

  • Mean = 0
  • Standard deviation = 1

Formula

\[ Z = \frac{X-\mu}{\sigma} \]

Where:

  • \(\mu\) = mean
  • \(\sigma\) = standard deviation

12. Normalization vs Standardization

Feature Normalization Standardization
Range 0 to 1 No fixed range
Mean Not fixed 0
Standard Deviation Not fixed 1
Outlier Sensitivity High Moderate
Best Used For Neural Networks Regression Models

13. Tobit Regression

Tobit regression is designed for censored dependent variables.

Examples:

  • Income censored at zero
  • Survey scores with upper limits
  • Measurements below detection thresholds
\[ Y_i^* = X_i \beta + \epsilon_i \]

Observed:

\[ Y_i = \begin{cases} Y_i^* & \text{if } Y_i^* > 0 \\ 0 & \text{otherwise} \end{cases} \]

14. Wald Chi-Square Test

The Wald test evaluates whether coefficients differ significantly from zero.

\[ \chi^2 = \left(\frac{\beta}{SE}\right)^2 \]

Where:

  • \(\beta\) = coefficient estimate
  • \(SE\) = standard error
Large Wald Chi-Square values imply statistically significant predictors.

15. Likelihood Ratio Test

Likelihood Ratio Test compares:

  • Full model
  • Restricted model
\[ \chi^2 = -2(LL_{restricted}-LL_{full}) \]

Where:

  • \(LL\) = Log-likelihood

If the statistic is large, the full model significantly improves prediction.


16. Python Examples

Chi-Square Test Example

import scipy.stats as stats

observed = [[20, 15, 10],
            [10, 25, 20]]

chi2, p, dof, expected = stats.chi2_contingency(observed)

print("Chi-Square:", chi2)
print("p-value:", p)
print("Degrees of Freedom:", dof)
print("Expected Frequencies:")
print(expected)

Tobit Regression Example

import numpy as np
import scipy.stats as stats
from tobit import TobitModel

model = TobitModel(y, X, left=0)
results = model.fit()

betas = results.params_
se = results.bse_

wald_chi2 = (betas / se) ** 2

p_values = 1 - stats.chi2.cdf(wald_chi2, df=1)

for i, (beta, chi2, p) in enumerate(zip(betas, wald_chi2, p_values)):
    print(f"Variable {i}: Chi-Square = {chi2:.4f}, p-value = {p:.4f}")

17. CLI Outputs

$ python chi_square_test.py

Chi-Square: 8.512
p-value: 0.014
Degrees of Freedom: 2

Result:
Reject the null hypothesis.
Variables are significantly associated.
$ python tobit_model.py

Variable 1:
Chi-Square = 14.8821
p-value = 0.0001

Variable 2:
Chi-Square = 0.9912
p-value = 0.3192

18. Interactive Learning Section

Expected frequencies represent what should occur if variables are independent. Comparing observed values to expected values helps determine whether relationships are statistically meaningful.

Degrees of freedom determine the correct Chi-Square distribution shape. Incorrect degrees of freedom lead to invalid statistical conclusions.

Normalization works best when features have bounded ranges or when neural networks and distance-based algorithms are used.

Ordinary regression fails with censored datasets. Tobit regression correctly handles variables limited by upper or lower thresholds.


19. Final Conclusion

Chi-Square testing is fundamental for categorical data analysis and hypothesis testing. It helps determine whether observed relationships are statistically significant or simply due to random variation.

Degrees of freedom ensure proper statistical interpretation, while normalization and standardization prepare datasets for machine learning algorithms.

Advanced models like Tobit regression extend statistical analysis into censored datasets, enabling researchers to analyze limited or constrained outcomes effectively.

Final Summary:
  • Chi-Square compares observed vs expected frequencies.
  • Degrees of freedom determine the statistical distribution.
  • Normalization rescales values between 0 and 1.
  • Standardization creates mean 0 and variance 1.
  • Tobit regression handles censored dependent variables.
  • Wald and Likelihood Ratio tests evaluate model significance.

Comparing Age Distributions: 2000 Census vs. 2010 Sample and Chi-Square Test Analysis





Chi-Square Test, Z Score, Standard Deviation & Age Distribution Explained

Chi-Square Test, Z Scores, Standard Deviation & Data Visualization Explained

Statistics forms the foundation of modern data science, machine learning, economics, demographics, and predictive analytics. Whether analyzing census data, customer behavior, medical trials, or business trends, understanding statistical concepts helps transform raw numbers into meaningful insights.

In this comprehensive guide, we will explore:

  • Chi-Square Test
  • Observed vs Expected Values
  • Z Scores
  • Standard Deviation
  • Demographic Analysis
  • Python Data Visualization
  • Histograms and Boxplots
  • Statistical Interpretation
Key Learning Goal:
By the end of this tutorial, you will understand how to compare distributions statistically, measure deviations from the mean, and visualize demographic patterns using Python.


1. Introduction to Statistical Distribution

Statistics helps us understand patterns within data. One of the most important questions analysts ask is:

Does the observed data behave the way we expected?

For example:

  • Did the population age distribution change?
  • Are customer preferences random or structured?
  • Are exam scores unusually high?
  • Is a sample representative of the population?

Statistical tests help answer these questions objectively.


2. What is Chi-Square Test?

The Chi-Square test is one of the most widely used statistical tests for categorical data.

It measures how different observed frequencies are from expected frequencies.

Main Purpose

  • Compare observed vs expected distributions
  • Test relationships between categorical variables
  • Identify statistically significant differences
\[ \chi^2 = \sum \frac{(O_i - E_i)^2}{E_i} \]

Where:

  • \(O_i\) = Observed frequency
  • \(E_i\) = Expected frequency

3. Observed vs Expected Values

Observed Value

Observed values are actual measurements collected from data.

Age Group Observed Count
Age 18 121
Age 18-35 288
Age >35 91

Expected Value

Expected values are theoretical counts assuming the historical proportions remain unchanged.

\[ E_i = p_i \times n \]

Where:

  • \(p_i\) = historical proportion
  • \(n\) = sample size
Age Group Expected Count
Age 18 100
Age 18-35 150
Age >35 250

4. Chi-Square Calculation

Now we calculate the difference between observed and expected values.

Step 1: Age 18

\[ \frac{(121 - 100)^2}{100} = \frac{441}{100} = 4.41 \]

Step 2: Age 18-35

\[ \frac{(288 - 150)^2}{150} = \frac{19044}{150} \approx 127.4 \]

Step 3: Age >35

\[ \frac{(91 - 250)^2}{250} = \frac{25281}{250} \approx 101.1 \]

Final Chi-Square Statistic

\[ \chi^2 = 4.41 + 127.4 + 101.1 = 232.91 \]

5. Interpreting Chi-Square Results

A large Chi-Square statistic means observed data differs significantly from expected data.

Degrees of Freedom

\[ df = k - 1 \]

Where:

  • \(k\) = number of categories

For 3 categories:

\[ df = 3 - 1 = 2 \]

Interpretation

  • Large Chi-Square → Significant difference
  • Small Chi-Square → Differences due to randomness
The 2010 sample strongly differs from the 2000 census distribution, suggesting a major demographic shift toward younger individuals.

6. Understanding Z Scores

Z Scores measure how far a value lies from the mean in terms of standard deviations.

\[ z = \frac{x - \mu}{\sigma} \]

Where:

  • \(x\) = observed value
  • \(\mu\) = mean
  • \(\sigma\) = standard deviation

Interpretation

Z Score Meaning
0 Exactly at mean
+1 1 standard deviation above mean
-1 1 standard deviation below mean
+2 Far above average
-2 Far below average

7. Standard Deviation Explained

Standard deviation measures how spread out data points are.

Formula

\[ \sigma = \sqrt{ \frac{ \sum (x_i - \mu)^2 }{n} } \]

Small standard deviation:

  • Data clustered near mean

Large standard deviation:

  • Data widely spread

Simple Example

Dataset A:

48, 49, 50, 51, 52

Very low standard deviation.

Dataset B:

10, 30, 50, 70, 90

Very high standard deviation.


8. Normal Distribution

Many real-world variables approximately follow a normal distribution.

\[ f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}} \]

Characteristics:

  • Bell-shaped curve
  • Mean = Median = Mode
  • Symmetrical distribution

68-95-99 Rule

  • 68% within 1 standard deviation
  • 95% within 2 standard deviations
  • 99.7% within 3 standard deviations

9. Variance and Dispersion

Variance measures average squared deviation from the mean.

\[ \sigma^2 = \frac{ \sum (x_i - \mu)^2 }{n} \]

Standard deviation is simply the square root of variance.


10. Python Visualization

Import Required Libraries

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

Create Sample Dataset

data = {
    'age': [25,30,22,35,40,28,50,19,60,45,32,37,29,23,41],
    'gender': [
        'Male','Female','Male','Female',
        'Male','Female','Male','Female',
        'Male','Female','Male','Female',
        'Male','Female','Male'
    ]
}

df = pd.DataFrame(data)

11. Histogram Visualization

Histograms show frequency distribution.

plt.figure(figsize=(10,6))

sns.histplot(
    data=df,
    x='age',
    hue='gender',
    kde=True,
    bins=10,
    alpha=0.6
)

plt.xlabel('Age')
plt.ylabel('Count')
plt.title('Age Distribution by Gender')

plt.show()

Explanation

  • hue separates gender categories
  • kde=True adds density curve
  • bins=10 divides age into intervals
  • alpha controls transparency

12. Boxplot Visualization

Boxplots summarize distributions compactly.

plt.figure(figsize=(8,6))

sns.boxplot(
    x='gender',
    y='age',
    data=df
)

plt.xlabel('Gender')
plt.ylabel('Age')
plt.title('Age Distribution by Gender')

plt.show()

Boxplot Components

  • Median
  • Quartiles
  • Interquartile range
  • Outliers

13. Advanced Statistical Concepts

P-Value

P-value measures probability of observing results assuming the null hypothesis is true.

\[ p < 0.05 \]

Usually considered statistically significant.

Hypothesis Testing

  • Null Hypothesis (\(H_0\))
  • Alternative Hypothesis (\(H_1\))

Sampling Error

Differences between sample statistics and population parameters.

Central Limit Theorem

\[ \bar{X} \sim N\left( \mu, \frac{\sigma}{\sqrt{n}} \right) \]

Large samples approximate normal distributions.


14. CLI Output Examples

Chi-Square Test Output

$ python chi_square_test.py

Observed:
[121, 288, 91]

Expected:
[100, 150, 250]

Chi-Square Statistic:
232.91

Degrees of Freedom:
2

P-value:
< 0.0001

Conclusion:
Reject the null hypothesis.
The distributions are significantly different.

Z Score Calculation Output

$ python zscore.py

Mean Age: 35
Standard Deviation: 8

Age Selected: 51

Z Score:
2.00

Interpretation:
The value is 2 standard deviations above the mean.

Interactive Learning Section

Standard deviation measures data variability. It helps determine whether observations are tightly grouped or highly dispersed.

Chi-Square compares category frequencies rather than continuous numerical values, making it ideal for demographic and survey analysis.

A large absolute Z score indicates an observation far from the average, potentially identifying unusual or rare events.


15. Final Conclusion

Statistics provides the mathematical language for understanding uncertainty, variation, and patterns in data.

The Chi-Square test helps determine whether observed categorical distributions differ significantly from expectations. Z Scores and standard deviation help measure how far observations deviate from the average.

Together, these concepts form the backbone of:

  • Machine Learning
  • Data Science
  • Forecasting
  • Business Analytics
  • Demographic Research
  • Economics
  • AI Systems
Final Learning Summary:
  • Chi-Square compares observed and expected frequencies.
  • Z Scores measure distance from the mean.
  • Standard deviation measures spread.
  • Histograms visualize frequency distributions.
  • Boxplots identify medians and outliers.
  • Python visualization improves statistical interpretation.
  • Statistical significance helps validate conclusions.

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts