1. Home
  2. Explore
  3. Engineering
  4. Regression Models & Hypothesis Testing

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Regression Models & Hypothesis Testing

Regression Models

Overview of Regression Analysis

Regression analysis (or regression models) is a group of statistical techniques that use existing data to estimate the relationship between a single dependent variable and one or more independent variables. The goal is to understand how variables are related, tell compelling stories, and influence decisions.

  • Dependent variable (Y): The variable being estimated (also called response or outcome variable). It is assumed to vary based on the values of the independent variables.

  • Independent variable (X): The variable whose trends are associated with the dependent variable (also called explanatory or predictor variable).

Regression models are flexible, interpretable, and highly marketable. They help answer questions like:

  • What variables impact sales?

  • What factors lead a customer to subscribe to a newsletter?

  • Why does a user keep scrolling on a website?


The PACE Framework

The PACE framework (Plan, Analyze, Construct, Execute) provides an organized structure for conducting regression analysis. It is iterative—data professionals may repeat or reorder steps as needed.

  • Plan: Understand the data and the problem context. Consider how data was collected, what business needs are, and what data is available.

  • Analyze: Examine the data closely (EDA) to choose an appropriate model. Check model assumptions—statements about the data that must be true to justify using a particular technique.

  • Construct: Build the model in Python. Select variables, transform data, write code, recheck assumptions, and evaluate preliminary results (e.g., "How good is my model?").

  • Execute: Interpret results, prepare formal visualizations, and share the story with stakeholders. Convert model statistics into clear descriptions of variable relationships.


Simple Linear Regression

Simple linear regression estimates the linear relationship between one continuous dependent variable Y and one independent variable X. The equation is:

Y=β0+β1XY = \beta_0 + \beta_1 XY=β0​+β1​X
  • β0\beta_0β0​ (beta-zero, or intercept): The value of Y when X = 0.

  • β1\beta_1β1​ (beta-one, or slope): The expected change in Y for a one-unit increase in X.

Correlation

When two variables X and Y are linearly related, they are correlated. Two types:

  • Positive correlation: Both variables increase or decrease together (e.g., more coffee purchases → more cake slices sold).

  • Negative correlation: One variable increases while the other decreases (e.g., longer articles → fewer readers finish).

Correlation is not causation. A relationship does not imply that one variable directly causes the other. Proving causation requires more rigorous methods.

Residuals and Ordinary Least Squares (OLS)

The best-fit line minimizes error between observed and predicted values.

  • Residual: The difference between an observed value and the predicted value for a given data point.

    ϵi=Yi−Y^i\epsilon_i = Y_i - \hat{Y}_iϵi​=Yi​−Y^i​
  • Sum of Squared Residuals (SSR): ∑(Yi−Y^i)2\sum (Y_i - \hat{Y}_i)^2∑(Yi​−Y^i​)2

  • Ordinary Least Squares (OLS): A method that minimizes the sum of squared residuals to estimate the parameters β0\beta_0β0​ and β1\beta_1β1​. Estimates are denoted with a hat: β^0\hat{\beta}_0β^​0​, β^1\hat{\beta}_1β^​1​.

Assumptions of Simple Linear Regression

Four key assumptions must be checked (some before model construction, some after):

  1. Linearity: The relationship between X and Y should appear as a straight line on a scatter plot.

  2. Normality of residuals: Residuals should be normally distributed (check with a Q-Q plot or histogram after fitting).

  3. Independent observations: Each observation is independent (assessed via data collection context).

  4. Homoscedasticity: The variance of residuals is constant across all fitted values (check a scatter plot of fitted values vs. residuals; no cone-shaped pattern).

Evaluation Metrics

  • R-squared (coefficient of determination): Proportion of variation in Y explained by X. Ranges from 0 to 1. Higher values indicate a better fit.

    R2=variance explained by modeltotal varianceR^2 = \frac{\text{variance explained by model}}{\text{total variance}}R2=total variancevariance explained by model​
  • Holdout sample: A random subset of data not used to fit the model, used to test performance on unseen data.

  • P-value: Tests the null hypothesis that the coefficient equals zero. A small p-value (typically < 0.05) suggests the relationship is statistically significant.

  • Confidence interval: Range of values that likely contains the true parameter (e.g., 95% CI).

  • Confidence band: The shaded region around the regression line representing uncertainty in predictions for every X value.

Interpretation Example

For penguin data: body mass (g) vs. bill length (mm).

  • Equation: body mass=−1707.29+141.19×bill length\text{body mass} = -1707.29 + 141.19 \times \text{bill length}body mass=−1707.29+141.19×bill length

  • Interpretation: A penguin with a bill 1 mm longer has, on average, 141.19 g greater body mass.

  • R-squared = 0.769 → bill length explains 77% of variance in body mass.

  • P-value < 0.001 → coefficient is statistically significant.


Multiple Linear Regression

Multiple linear regression (or multiple regression) estimates the linear relationship between one continuous dependent variable Y and two or more independent variables.

Y=β0+β1X1+β2X2+⋯+βnXnY = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \dots + \beta_n X_nY=β0​+β1​X1​+β2​X2​+⋯+βn​Xn​
  • Allows asking more complex questions (e.g., how do holidays, product launches, and marketing campaigns affect sales?).

  • Interpretation requires holding other variables constant: "For a one-unit increase in X1X_1X1​, holding all other variables constant, Y changes by β1\beta_1β1​."

Handling Categorical Variables: One-Hot Encoding

One-hot encoding transforms a categorical variable into several binary (0/1) variables. For a variable with kkk categories, create k−1k-1k−1 binary variables (the omitted category becomes the baseline). Example: Ad platform (A, B, C) → create variables X_serviceA and X_serviceB; service C is the reference.

Interaction Terms

An interaction term captures how the relationship between two independent variables affects Y. Represented as the product of the two variables (e.g., temperature×distance\text{temperature} \times \text{distance}temperature×distance). It allows the effect of one variable to depend on the level of another.

New Assumption: No Multicollinearity

Multicollinearity occurs when two or more independent variables are highly correlated. This makes it difficult to isolate each variable’s effect and inflates standard errors. Check using:

  • Scatter plot matrix (pairwise plots)

  • VIF (Variance Inflation Factor): minimum = 1; larger values indicate more multicollinearity. Common threshold: VIF > 5–10 is problematic.

  • Solutions: drop one of the correlated variables or create a composite variable.

Evaluation: Adjusted R-squared and Overfitting

  • Adjusted R-squared: A modified version of R² that penalizes adding unnecessary variables. Prevents overfitting—when a model fits the training data too specifically and fails to generalize to new data.

  • Overfitting tends to occur with too many variables or overly complex models. Use holdout sampling and adjusted R² to detect it.

Variable Selection Techniques

  • Forward selection: Start with no variables; add the most statistically significant predictor one at a time (based on a chosen metric like extra-sum-of-squares F-test) until no improvement.

  • Backward elimination: Start with all variables; remove the least significant predictor one at a time until only significant ones remain.

  • Extra-sum-of-squares F-test: Compares the variance explained by a reduced model vs. a full model; used to decide whether adding or removing a variable significantly improves fit.

Regularization and the Bias-Variance Tradeoff

Regularization shrinks coefficient estimates toward zero, adding bias to reduce variance and prevent overfitting. Three common techniques:

  • Lasso regression: Can force some coefficients to exactly zero, effectively removing variables.

  • Ridge regression: Minimizes coefficients but never reduces them to zero; keeps all variables.

  • Elastic-net regression: Combines Lasso and Ridge penalties.

The bias-variance tradeoff balances model simplicity (bias) against flexibility (variance). High bias underfits; high variance overfits. Regularization helps find the sweet spot.


Hypothesis Testing for Categorical Variables

Chi-Squared Tests

  • Chi-squared goodness-of-fit test: Determines whether an observed categorical variable follows an expected distribution.

    • Null hypothesis: The variable follows the expected distribution.

    • Test statistic: χ2=∑(Oi−Ei)2Ei\chi^2 = \sum \frac{(O_i - E_i)^2}{E_i}χ2=∑Ei​(Oi​−Ei​)2​ where OiO_iOi​ = observed count, EiE_iEi​ = expected count.

  • Chi-squared test of independence (test of homogeneity): Determines whether two categorical variables are associated.

    • Null hypothesis: The variables are independent.

    • Expected cell count: row total×column total/grand total\text{row total} \times \text{column total} / \text{grand total}row total×column total/grand total.

ANOVA (Analysis of Variance)

ANOVA tests whether the means of a continuous variable differ across three or more groups (categorical independent variable). It is an extension of the t-test.

  • One-way ANOVA: Compares means of one continuous DV across levels of one categorical IV.

    • Null hypothesis: μ1=μ2=⋯=μk\mu_1 = \mu_2 = \dots = \mu_kμ1​=μ2​=⋯=μk​ (all group means equal).

  • Two-way ANOVA: Compares means based on two categorical IVs, including their interaction.

    • Tests three pairs of hypotheses: main effects of each IV and the interaction effect.

Post-hoc test (e.g., Tukey’s HSD): After an ANOVA shows significance, this test performs pairwise comparisons while controlling for multiple testing (Type I error inflation).

ANCOVA, MANOVA, MANCOVA

  • ANCOVA (Analysis of Covariance): Compares means across groups while controlling for one or more continuous covariates (e.g., controlling for temperature when comparing weekend vs. weekday coffee sales).

  • MANOVA (Multivariate Analysis of Variance): Compares two or more continuous outcome variables across groups (e.g., both sales and profit across genres).

  • MANCOVA (Multivariate Analysis of Covariance): Combines MANOVA and ANCOVA, controlling for covariates while testing multiple outcomes.


Logistic Regression

Logistic regression models the probability that a categorical dependent variable (often binary) occurs, based on one or more independent variables. It uses a link function (logit) to relate the predictors to the probability.

Binomial Logistic Regression

Models the probability of one of two outcomes (Y = 0 or 1). Key concepts:

  • Odds: P(Y=1)1−P(Y=1)\frac{P(Y=1)}{1 - P(Y=1)}1−P(Y=1)P(Y=1)​

  • Logit (log-odds): log⁡(P1−P)\log\left(\frac{P}{1-P}\right)log(1−PP​)

  • The logistic regression model assumes a linear relationship between the logit of the probability and the X's:

    logit(P)=β0+β1X1+⋯+βnXn\text{logit}(P) = \beta_0 + \beta_1 X_1 + \dots + \beta_n X_nlogit(P)=β0​+β1​X1​+⋯+βn​Xn​

Maximum Likelihood Estimation (MLE)

MLE finds the set of β\betaβ coefficients that maximize the likelihood of observing the sample data. Likelihood is the probability of the observed data given the parameters. Observations are assumed independent, so the total likelihood is the product of individual likelihoods.

Assumptions of Logistic Regression

  1. Linearity: Each X must be linearly related to the logit of the probability of Y=1 (not to Y itself).

  2. Independence of observations (from data collection).

  3. Little to no multicollinearity among predictors.

  4. No extreme outliers (can be checked after model fitting).

Evaluation Metrics

  • Confusion Matrix: Shows true positives (TP), true negatives (TN), false positives (FP), false negatives (FN).

  • Precision: TPTP+FP\frac{TP}{TP+FP}TP+FPTP​ — proportion of positive predictions that were correct.

  • Recall (sensitivity): TPTP+FN\frac{TP}{TP+FN}TP+FNTP​ — proportion of actual positives correctly identified.

  • Accuracy: TP+TNTP+TN+FP+FN\frac{TP+TN}{TP+TN+FP+FN}TP+TN+FP+FNTP+TN​ — overall proportion of correct predictions.

  • ROC curve and AUC: Plot true positive rate vs. false positive rate at various thresholds; AUC summarizes model performance across thresholds.

Interpretation of Coefficients

  • Exponentiate the coefficient (eβe^{\beta}eβ) to get the odds ratio.

  • For a one-unit increase in X, the odds of Y=1 change by (eβ−1)×100%e^{\beta} - 1) \times 100\%eβ−1)×100%.

  • Example: β=−0.118\beta = -0.118β=−0.118 → e−0.118=0.89e^{-0.118} = 0.89e−0.118=0.89 → odds decrease by 11% per unit increase in vertical acceleration.

  • When multiple predictors exist, interpret "holding other variables constant."

Model Building in Python (Scikit-learn / Statsmodels)

  • Use LogisticRegression() from scikit-learn for classification; get coefficients via .coef_ and .intercept_.

  • Use predict() (returns 0/1 labels) and predict_proba() (returns probabilities).

  • For p-values and confidence intervals, use Statsmodels' Logit or GLM.

  • Plot logistic regression curve using seaborn.regplot(logistic=True).


Summary and Next Steps

  • Linear regression models continuous outcomes; logistic regression models categorical outcomes (probabilities).

  • The PACE framework guides all modeling: Plan → Analyze → Construct → Execute.

  • Always check model assumptions before and after fitting.

  • Use appropriate evaluation metrics (R², adjusted R², confusion matrix, precision, recall) to assess model quality.

  • Hypothesis testing (chi-squared, ANOVA, etc.) helps compare groups and validate assumptions.

  • Regularization combats overfitting in multiple regression.

These skills prepare data professionals to uncover relationships, tell honest stories, and influence business decisions across industries. They also form the foundation for more advanced machine learning topics.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent