Advanced Regression Methods
Review of Simple Linear Regression
Simple linear regression models the relationship between one dependent variable (outcome) and one independent variable (predictor). The goal is to find a straight line that best describes how changes in the predictor affect the outcome – a best‑fit line.
where is the predicted dependent variable, the independent variable, the intercept, and the slope (the estimated change in per unit change in ).
Intuition: Quantify and predict a one‑factor influence.
Business examples:
- Predict sales based on advertising spend.
- Forecast monthly revenue from foot traffic.
- Estimate fuel consumption from distance driven.
Multiple Linear Regression
Multiple linear regression extends the idea to multiple independent variables simultaneously:
Why it matters: Real‑world outcomes are rarely driven by a single factor. Multiple regression disentangles the joint effect of several predictors.
Business examples:
- Real estate: House price depends on location, bedrooms, amenities.
- Finance: Credit score assessment using income, employment status, debt level.
- Sales prediction: Price, economic conditions, number of competitors all matter.
Exam tip: Simple regression is a special case of multiple regression (). All assumptions and diagnostic checks apply to both.
Comparison of Simple vs. Multiple Linear Regression
| Aspect | Simple Linear Regression | Multiple Linear Regression |
|---|---|---|
| Number of predictors | One | Two or more |
| Model equation | ||
| Use case | Single‑factor influence | Multi‑factor influence |
| Business complexity | Low (e.g., ad spend → sales) | High (e.g., house pricing) |
Key takeaways – Simple & Multiple Regression
- Both provide a structured way to quantify relationships and predict outcomes.
- Simple regression handles one predictor; multiple regression handles many.
- Effective for forecasting, resource allocation, and identifying key drivers.
- Reliability depends on assumptions (next section).
Key Assumptions of Linear Regression
Validity of linear regression rests on several assumptions. When any is violated, predictions and inferences become biased.
1. Linearity
The relationship between predictors and the dependent variable must be linear – a constant change in produces a constant change in .
- Violation example: Advertising spend often shows diminishing returns; initial dollars yield steep sales increases, later dollars yield little. The true relationship is curved, not a straight line.
2. Independence of Residuals
Residuals (errors = observed – predicted) must be independent of each other.
- Violation example: Time‑series data – today’s stock price depends on yesterday’s, leading to correlated errors.
3. Homoscedasticity
The variance of residuals should be constant across all levels of the predictors.
- Violation (heteroscedasticity): As income increases, spending variability tends to rise – wealthier individuals have more diverse habits.
4. Normality of Error Terms
Residuals should follow a normal distribution (critical for confidence intervals and hypothesis tests).
- Violation: Many real‑world datasets are skewed or have outliers. For continuous non‑normal data, consider transformation; for binary outcomes, switch to logistic regression.
5. No Multicollinearity
Independent variables should not be highly correlated with each other.
- Violation example: Advertising spend and marketing spend are often strongly correlated, making it impossible to isolate each variable’s unique effect on sales.
| Assumption | Description | Business violation example |
|---|---|---|
| Linearity | Predictor–outcome relationship is a straight line | Advertising with diminishing returns |
| Independence | Residuals not correlated over time | Stock prices; time‑series data |
| Homoscedasticity | Constant residual variance | Income vs. spending; richer people show more variability |
| Normality | Residuals are normally distributed | Skewed data or binary outcomes |
| No multicollinearity | Predictors not highly correlated | Advertising spend & marketing spend |
Key takeaways – Assumptions
- Violations lead to biased estimates, invalid hypothesis tests, and poor predictions.
- Each assumption points to a specific advanced technique (e.g., logistic regression for binary outcomes; nonlinear regression for curvature).
- Always test assumptions before relying on linear regression results.
When Assumptions Fail: Introduction to Advanced Methods
When linear regression’s assumptions are not met, two common alternatives are introduced:
flowchart TD
A[Regression Problem] --> B{Assumptions hold?}
B -->|Yes| C[Use Linear Regression]
B -->|No| D{Type of failure?}
D -->|Binary outcome OR non‑normal errors| E[Logistic Regression]
D -->|Non‑linear relationship| F[Non‑linear Regression]
Logistic Regression
Used when the dependent variable is categorical – often binary (yes/no, success/failure).
- Linear regression is inappropriate because it assumes a continuous outcome and can predict probabilities outside [0,1].
- Logistic regression models the probability of an event using a logistic (S‑shaped) function, ensuring predictions fall between 0 and 1.
- Business applications: predict customer purchase (yes/no), loan default, employee retention.
Non‑linear Regression
Used when the relationship between variables is inherently non‑linear.
- Examples: price–demand curves (small price changes cause large demand shifts at certain points), drug dosage–response (diminishing effects at high doses).
- Common forms: polynomial, exponential, logarithmic models.
Exam tip: If the dependent variable is binary, always choose logistic regression over linear regression – even if other assumptions hold. The linear model will produce nonsense probabilities.
Key takeaways – Advanced Methods
- Logistic regression handles binary outcomes; models probability via a logistic curve.
- Non‑linear regression captures curvilinear relationships that linear models cannot fit.
- These methods preserve the interpretability and predictive power that linear regression offers, but under more realistic conditions.
Linear Regression for Two-Sample Comparison of Means
Intuition: Comparing the means of two independent groups (e.g., before/after a campaign, with/without an accident) is typically done with a two-sample t-test. The same test can be performed using linear regression with a binary dummy variable that encodes group membership. This may seem roundabout, but it pays off: once the comparison is embedded in a regression framework, we can easily add control variables, extend to multiple groups, and link to more advanced models like fixed effects and interaction effects.
Setup
- Dependent variable : continuous outcome (e.g., satisfaction level).
- Independent variable : binary (0 or 1) indicating group membership.
- : reference group (e.g., no accident at work).
- : comparison group (e.g., had an accident).
Model:
Interpretation of Coefficients
| value | Expected | Interpretation |
|---|---|---|
| Mean of reference group | ||
| Mean of comparison group | ||
| Difference | Mean difference (comparison group minus reference group) |
Thus:
- Testing whether is significantly different from zero is equivalent to testing whether the two group means differ.
- The sign of indicates which group has the higher mean.
Worked Example: Accidents and Job Satisfaction
Question: Do employees who experienced an accident at work have a different average satisfaction level than those who did not?
Data: HR dataset containing satisfaction_level (continuous) and any_accident (1 = yes, 0 = no).
Simple linear regression output (from Excel):
| Coefficient | Estimate | Std. Error | p-value |
|---|---|---|---|
| Intercept () | 0.607 | ... | <0.05 |
any_accident () | 0.041 | 0.006 | <0.05 |
- : mean satisfaction of employees without an accident.
- : employees with an accident have a mean satisfaction that is 0.041 (≈4%) higher.
- The coefficient is statistically significant → the mean difference is real.
Exam tip: A regression with a single binary predictor produces exactly the same p‑value as an independent-samples t-test for the mean difference. The regression approach becomes superior when you need to control for additional variables.
Why This Result Might Be Surprising
The positive sign (accident → higher satisfaction) is counter‑intuitive. A possible explanation is confounding: employees who have accidents may also work in different departments, have different workloads, or be treated differently by the company. The simple regression cannot separate the effect of the accident from these other factors.
Controlling for Confounders: Multiple Regression
Add covariates that capture workload and experience:
number_projectsandaverage_monthly_hours(workload)years_at_companyandpromotion_last_5years(experience)
Model:
Result: The coefficient for any_accident remains about 0.041 and statistically significant. Even after controlling for workload and experience, the positive relationship persists. This strengthens the evidence that the accident effect is genuine (perhaps due to company support policies), though further investigation is warranted.
Key advantage over a t-test: The regression framework naturally controls for multiple covariates, reducing omitted‑variable bias and yielding a more reliable estimate of the causal effect (under appropriate assumptions).
Connections to Advanced Topics
- Fixed effects: Using dummy variables for each individual (or group) to control for all time‑invariant unobservable characteristics. The regression shown is a simple fixed‑effects model at the group level (accident vs. no accident). In panel data, each subject gets its own dummy, isolating within‑subject variation.
- Interaction effects: The effect of the binary variable may differ across levels of another variable (e.g., salary). For example, an accident might lower satisfaction for low‑paid employees but not for high‑paid ones. This is modelled by adding an interaction term (e.g.,
accident × salary) to the regression.
Key Takeaways
- A simple linear regression with a binary dummy variable performs a two‑sample comparison of means.
- = mean of reference group; = mean difference (comparison minus reference).
- A significant indicates a statistically significant difference between groups.
- The sign of reveals which group has the higher mean.
- Multiple regression allows controlling for confounders, a major advantage over a standard t-test.
- Dummy variable regression is the foundation for fixed effects models and interaction effects.
From Two Samples to Multiple Groups
A linear regression model can compare means across more than two independent groups, just as it does for two samples. Intuitively: instead of running a one-way ANOVA, we regress the outcome on a set of binary (dummy) variables that encode group membership, and test whether the group differences are statistically significant.
This approach treats the outcome as a continuous variable (unlike a chi‑square test of independence, which would require binning the continuous outcome into categories). The regression model directly estimates group means and their differences.
Dummy Variable Setup for Groups
- Create binary columns, one per group (e.g.,
Low,Medium,High). - Choose one group as the baseline (reference) category – omit its dummy from the model.
- The intercept estimates the mean of the baseline group.
- Each other coefficient estimates the difference between the mean of group and the baseline mean.
Example: Salary Level and Satisfaction
A dataset of 14,999 employees has salary categorised as Low, Medium, or High. The satisfaction level (0–1) is the dependent variable. To test whether mean satisfaction differs by salary group:
- Create dummy variables:
Low(=1 if salary=Low),Medium,High. - Set baseline: e.g.,
Lowis the reference group – omit it from the model. - Run regression: satisfaction ~
Medium+High(plus intercept).
| Variable | Coefficient | Interpretation |
|---|---|---|
| Intercept | Mean satisfaction of low‑salary employees ≈ 0.600 (i.e., 60% satisfied). | |
Medium | (significant) | Medium‑salary employees are on average 2.1% more satisfied than low‑salary. |
High | (significant) | High‑salary employees are on average 3.7% more satisfied than low‑salary. |
Thus:
- Low salary mean = 60.0%
- Medium salary mean = 60.0% + 2.1% = 62.1%
- High salary mean = 60.0% + 3.7% = 63.7%
A coefficient that is significantly different from zero (via its ‑statistic / ‑value) indicates that the group mean differs from the baseline. The sign tells the direction.
Exam tip: Always set the baseline to a meaningful group (e.g., the most common or a control). The interpretation of the intercept and all other coefficients depends on that choice.
Key Takeaways
- Dummy variables convert categorical membership into numeric predictors.
- One category is always omitted – it becomes the baseline (intercept).
- Coefficients on the included dummies represent mean differences relative to baseline.
- A significant coefficient implies the group’s mean is statistically different from baseline.
- The same logic extends the two‑sample ‑test to multiple groups (equivalent to one‑way ANOVA).
Interaction Effects: Does Salary’s Impact Vary by Department?
The transcript asks: Do employees from different departments place equal emphasis on salary when reporting satisfaction? To answer this, we include an interaction term – a variable that captures the joint effect of two categorical predictors.
Intuition
A simple additive model assumes the salary effect is the same across departments. An interaction model allows the slope (difference between salary groups) to differ by department. For example, sales employees might value salary more than R&D employees, for whom job security matters more.
How to Build an Interaction Model (in Excel)
- Create dummy variables for every combination of the two categorical variables.
- Example: 10 departments × 3 salary levels = 30 dummy columns (e.g.,
Sales_Low,Sales_Medium,Sales_High,HR_Low, …).
- Example: 10 departments × 3 salary levels = 30 dummy columns (e.g.,
- Choose a baseline combination – e.g.,
HR_Low– and omit it from the regression. - Run the regression with all remaining 29 dummy variables as predictors.
Practical Concern – Sparse Cells
If a combination has very few observations (e.g., only 2 management employees with low salary), its coefficient will be unreliable. A recommended workaround: drop dummy columns for those sparse interactions. You will still capture the overall effect for that department but sacrifice the ability to estimate the interaction precisely.
Interpreting the Output
- Each interaction coefficient measures the difference in mean satisfaction for that specific (department, salary) combination relative to the baseline combination.
- Joint significance test (e.g., ‑test on all interaction dummies) tells whether including them significantly improves the model.
- If the interaction effects are significant: salary’s influence on satisfaction depends on department.
- If not: salary has a similar impact across all departments – the additive model suffices.
Exam tip: Interaction terms answer the question “Does the effect of X on Y depend on Z?” When Z is categorical, you need dummies for every X‑by‑Z cell. Always check for sparse cells; drop them to maintain reliable estimates.
Key Takeaways
- Interaction effects capture how the relationship between the dependent variable and one categorical predictor changes across levels of another categorical predictor.
- Implementation: create dummy variables for every combination of the two categories, then regress on those dummies (minus one baseline).
- Sparse cells (few observations) produce unreliable coefficients – consider dropping those dummy columns.
- Significant interactions imply the effect of salary differs by department; non‑significant interactions imply uniform effect.
Logistic Regression Model - I
Logistic regression is a technique for modeling the probability of a binary outcome (e.g., yes/no, success/failure, leave/stay) as a function of one or more independent variables.
It is the natural choice when the dependent variable is categorical – unlike linear regression, which assumes a continuous response.
Why linear regression fails for binary outcomes
- A binary outcome (coded or ) follows a Bernoulli distribution.
- Linear regression would model . Because a line is unbounded, predicted probabilities can fall outside – nonsensical for a probability.
- Logistic regression fixes this by applying the logistic (sigmoid) function, which maps any real-valued input to .
flowchart LR
A[Binary outcome Y ∈ {0,1}] --> B[Linear regression<br>predicts continuous values]
B --> C[Predictions outside 0-1]
A --> D[Logistic regression<br>models P(Y=1) via sigmoid]
D --> E[Predictions always in 0-1]
The logistic (sigmoid) function
- The curve is S‑shaped: for very low or very high , the probability flattens near or .
- The sign of determines the direction: positive → increasing probability as rises; negative → decreasing.
Foundation: Bernoulli distribution
- A binary variable follows a Bernoulli distribution: , .
- Logistic regression estimates as a function of the independent variables, ensuring .
Odds and log odds
Odds of success:
- If , odds (equal chance).
- If , odds ; if , odds .
Log odds (logit):
- Spans the entire real line: when , when .
- Logistic regression models log odds as a linear function of the independent variables:
Exam tip: Linear regression models the mean directly; logistic regression models the log odds linearly. This linearity in log odds is what makes coefficients interpretable as changes in log odds per unit predictor increase.
Worked example: Instagram users by gender
Data: 1069 survey respondents (537 men, 532 women).
328 women and 234 men have Instagram accounts.
| Gender | Users | Total | Proportion | Odds | Log odds |
|---|---|---|---|---|---|
| Women | 328 | 532 | |||
| Men | 234 | 537 |
Define for women, for men.
Logistic regression assumes:
Plugging in the log odds:
- For men ():
- For women ():
Estimated model:
Convert back to probability:
- For women (): (matches data).
- For men (): .
Exam tip: The coefficient is the difference in log odds between women and men. A positive means higher log odds (and thus higher probability) for the group coded .
Business applications
- Marketing: Predict whether a customer buys a product (based on demographics, browsing data).
- Credit scoring: Classify loan applicants as likely to default or repay.
- HR: Model employee attrition (e.g., probability of leaving given satisfaction level).
In all cases, logistic regression outputs a probability between 0 and 1, which can be used for classification with a chosen threshold (e.g., >0.5 → “will leave”).
Key takeaways
- Logistic regression models binary outcomes using the logistic (sigmoid) function to keep predicted probabilities in .
- It is built on the Bernoulli distribution.
- Instead of predicting directly, it models the log odds linearly: .
- The odds are ; log odds are the natural log of that ratio.
- Coefficients represent the change in log odds for a one‑unit increase in .
- Linear regression fails because it can produce probabilities outside .
- The sigmoid curve ensures valid probabilities: S‑shaped, flat near 0 and 1.
Logistic Regression Model - II
Logistic regression predicts the probability of a binary outcome (success/failure, quit/stay, buy/not buy). Unlike linear regression, it models the log odds of the event as a linear function of predictors, ensuring predictions stay between 0 and 1.
From linear combination to log odds
For multiple predictors , the logistic regression equation expresses the log odds:
- = probability the event occurs (e.g., employee leaves)
- = intercept (log odds when all = 0)
- = coefficients measuring the effect of each predictor on log odds
Using log odds solves the range problem: probability is bounded , but log odds can take any real value , so the linear model can fit without constraints.
The logistic (sigmoid) function
Rearranging the equation gives probability directly:
This is the logistic function (or sigmoid). It produces an S‑shaped curve that smoothly increases from 0 to 1 as the linear combination changes.
Definition: The logistic function maps any real input to a probability between 0 and 1 — essential for binary classification.
Interpreting coefficients
- A positive coefficient means an increase in increases the log odds (and thus the probability) of the outcome.
- A negative coefficient means an increase in decreases the log odds.
- Because the relationship between and is non‑linear, the change in probability per unit change in is not constant — it depends on the current value of . However, the direction (positive/negative) is fixed.
Exam tip: Logistic regression coefficients refer to log odds, not probability. To get the effect on odds, exponentiate the coefficient: gives the odds ratio.
Estimating coefficients: Maximum Likelihood Estimation (MLE)
Linear regression uses least squares; logistic regression uses maximum likelihood estimation (MLE).
Intuition: The model tries many possible coefficient values. For each set, it computes the predicted probability for every observation. Then it compares these probabilities to the actual binary outcomes (0 or 1). The goal is to find the coefficient values that make the observed data most likely — i.e., that maximize the likelihood of seeing the actual outcomes.
Procedure:
- Start with initial guesses for s.
- Compute predicted probabilities via the logistic function.
- Calculate the likelihood (a measure of how well predictions match real outcomes).
- Adjust coefficients iteratively to increase the likelihood.
- Stop when improvement becomes negligible — the maximum likelihood estimates.
flowchart LR
A[Choose initial β] --> B[Compute predicted probabilities]
B --> C[Calculate likelihood]
C --> D{Maximum reached?}
D -- No --> E[Update β]
E --> B
D -- Yes --> F[Final β estimates]
This iterative search can be performed in Excel using the Solver add‑in, by setting up the likelihood function and maximizing it.
Implementation in Excel
For a dataset with one binary outcome and predictors:
- Use the logistic function to compute predicted probabilities for each row.
- Construct the log‑likelihood formula (sum of log probabilities for observed outcomes).
- Run Solver to maximize the log‑likelihood by changing the coefficient cells.
Exam tip: Solver finds the same coefficients that statistical software (R, Python, SPSS) produces — it's a good way to see MLE in action without coding.
Key takeaways
- Logistic regression models the log odds of a binary outcome.
- The sigmoid function turns the linear combination into a probability .
- Coefficients indicate direction (positive/negative) on log odds; the effect on probability is non‑linear.
- Maximum likelihood estimation iteratively finds the best coefficients by maximizing the probability of observing the data.
- In Excel, Solver can be used to perform MLE for small problems.
Intuition and Problem Setup
Logistic regression models a binary outcome (e.g., leave / stay) as a function of one or more predictors. Here the goal is to predict employee attrition (1 = left, 0 = stayed) from satisfaction level (0 to 1). The relationship is non‑linear: probability of leaving is linked to the predictors via the logistic function:
Equivalently, the log‑odds (logit) of the event is linear:
The coefficients are estimated by maximum likelihood – an iterative search that finds the values making the observed data most probable.
Step‑by‑Step Estimation in Excel
The data (columns A, B) contain the binary outcome (A) and satisfaction (B). The Excel implementation proceeds as follows.
1. Compute Log‑Odds
Place initial guesses for and in cells (e.g., H2, I2). For each row :
In Excel: = $H$2 + $I$2 * B2 (copied down).
2. Convert Log‑Odds → Odds → Probability
Then the predicted probability depends on the actual outcome:
- If :
- If :
Excel: = IF(A2=1, D2/(1+D2), 1/(1+D2)).
3. Log‑Likelihood
Because probabilities multiply across independent observations (product → very small), we work with logs:
Sum all to get the total log‑likelihood (cell, e.g., J2).
4. Optimization with Solver
Goal: maximize the total log‑likelihood by changing and .
- Open Solver (Data → Solver).
- Set Objective: cell containing sum of log‑likelihood.
- To: Max.
- By Changing Variable Cells: the , cells.
- Select Solving Method: GRG Nonlinear.
- Click Solve.
Excel iterates through coefficient combinations and returns the maximum‑likelihood estimates.
flowchart LR
A[Data: y, x] --> B[Log-odds = β₀ + β₁x]
B --> C[Odds = exp(log-odds)]
C --> D{Outcome y?}
D -->|y=1| E[P = odds/(1+odds)]
D -->|y=0| F[P = 1/(1+odds)]
E --> G[Log-likelihood = ln(P)]
F --> G
G --> H[Sum log-likelihood]
H --> I[Maximize with Solver]
I --> J[MLE coefficients β₀, β₁]
Results and Interpretation
Single Variable Model
The solver yields:
| Coefficient | Estimate |
|---|---|
| (intercept) | 0.974 |
| (satisfaction) | –3.832 |
Thus the estimated model:
Interpretation:
-
Sign of is negative → higher satisfaction lowers the odds of quitting.
-
Magnitude cannot be directly read as a change in probability (non‑linear). Instead compute predicted probability at key satisfaction values:
Satisfaction Predicted probability of leaving 0 (not at all satisfied) (72 %) 1 (fully satisfied) (4–5 %) -
The decrease is non‑linear: probability drops steeply at low satisfaction and flattens at high satisfaction.
Multiple Variable Model (Extension)
The same Solver approach extends to several predictors. For a model including:
- satisfaction level
- last performance evaluation rating
- average monthly hours
- years at company
- promotion in last 5 years (coded 1/0)
| Variable | Coefficient (approx.) | Sign | Interpretation |
|---|---|---|---|
| Satisfaction | –3.7 | – | More satisfied → less likely to leave |
| Promotion in last 5 years | large negative | – | Promoted employees much less likely to leave |
| Years at company | positive (largest magnitude) | + | Longer tenure → higher chance of leaving (retirement / better offers) |
| Average monthly hours | positive | + | Higher workload → higher chance of leaving |
| Last evaluation rating | positive | + | Higher rating → more likely to leave (counterintuitive – possible reasons: felt under‑rewarded, better external opportunities) |
Exam tip: The sign of a logistic coefficient tells the direction of effect on the log‑odds of the outcome. To express effect on probability, compute predicted at different values. Never interpret a coefficient as a linear change in probability.
Key takeaways
- Logistic regression models binary outcomes via the logit link: .
- Estimation uses maximum likelihood – iterative maximization of the sum of log‑likelihoods.
- In Excel: compute log‑odds → odds → probability (conditional on outcome) → log‑likelihood → maximize with Solver (GRG Nonlinear).
- Coefficient sign indicates direction: negative → predictor reduces odds of event.
- For multiple predictors, each coefficient is interpreted holding others constant; magnitude comparison gives relative importance.
- Counterintuitive signs (e.g., positive coefficient for performance rating) can reveal hidden dynamics – use domain knowledge to hypothesise.
Logistic Regression – Using Excel with Dummy Variables
When a categorical predictor (e.g., salary level) has ( k ) categories, it enters a logistic regression as ( k-1 ) dummy variables. One category is chosen as the baseline; the coefficients on the dummies measure the change in log‑odds relative to that baseline.
Setting Up Dummy Variables
- Salary has three categories: low, medium, high.
- Set low as baseline → create two dummies:
- ( x_{\text{medium}} = 1 ) if medium salary, else 0
- ( x_{\text{high}} = 1 ) if high salary, else 0
The logistic regression then includes these dummies alongside continuous predictors.
Model Specification
Eight independent variables are used:
| Variable | Type | Description |
|---|---|---|
| satisfaction_level | continuous (0–1) | Employee satisfaction |
| last_evaluation | continuous (0–1) | Last performance rating |
| average_monthly_hours | continuous | Workload (hours/month) |
| years_at_company | integer | Tenure |
| promotion | binary (0/1) | Received promotion in last year? |
| salary_medium | dummy | 1 if medium salary |
| salary_high | dummy | 1 if high salary |
| (plus intercept) | — | ( \beta_0 ) |
Parameters: ( \beta_0, \beta_1, \dots, \beta_7 ).
Log‑odds for employee ( i ):
[ \text{logit}(p_i) = \ln\left(\frac{p_i}{1-p_i}\right) = \beta_0 + \beta_1 x_{i1} + \cdots + \beta_7 x_{i7} ]
The model is fitted by maximizing the sum of log‑likelihoods (using Excel Solver).
Interpretation of Coefficients (Transcript‑Based)
The exact values are not given, but the sign and relative magnitude are discussed.
| Variable | Sign | Interpretation |
|---|---|---|
| satisfaction_level | negative, large magnitude | Higher satisfaction → much less likely to leave |
| promotion | negative, large magnitude | Promotion → much less likely to leave |
| salary_medium | negative | vs low‑salary baseline: medium‑salary employees are less likely to leave |
| salary_high | negative, larger magnitude than medium | High‑salary employees are even less likely to leave than medium |
| years_at_company | positive, substantial magnitude | Longer tenure → more likely to leave (perhaps for better prospects) |
| last_evaluation | diminished after including salary/promotion | Becomes secondary once satisfaction and salary are controlled |
| average_monthly_hours | diminished | Similarly secondary |
Key insight: Satisfaction, salary, and promotion dominate the prediction; evaluation and hours matter less once these are accounted for.
Worked Example: What‑If Analysis
Employee profile:
| Variable | Value |
|---|---|
| satisfaction_level | 0.5 (50%) |
| last_evaluation | 0.7 |
| average_monthly_hours | 250 |
| years_at_company | 1 |
| promotion | 0 |
| salary | low → ( x_{\text{medium}}=0,; x_{\text{high}}=0 ) |
Prediction (using previously estimated coefficients):
Compute log‑odds:
[ \begin{aligned} \text{log‑odds} &= \beta_0 + \beta_1(0.5) + \beta_2(0.7) + \beta_3(250) + \beta_4(1) \ &\quad + \beta_5(0) + \beta_6(0) + \beta_7(0) \ &= -1.075 \end{aligned} ]
Convert to probability:
[ p = \frac{e^{-1.075}}{1+e^{-1.075}} \approx 0.254 \quad (25.4%) ]
Scenario Testing
Change one variable at a time and recompute ( p ) (hypothetical outcomes from transcript):
| Scenario | Change | New ( p ) | Interpretation |
|---|---|---|---|
| Raise salary to medium | ( x_{\text{medium}}=1 ) | 16.8% | Quit risk drops ◄ |
| Raise salary to high | ( x_{\text{high}}=1 ) | 4.7% | Quit risk very low ◄◄ |
| Give promotion | ( x_{\text{promotion}}=1 ) | (substantial reduction) | Promotion also strongly reduces leaving |
Business use: the HR department can estimate the impact of each intervention and choose the most cost‑effective strategy.
flowchart LR
A[Employee profile] --> B[Logistic model]
B --> C[Baseline probability 25.4%]
C --> D{Intervention?}
D --> E[Increase salary to medium]
D --> F[Increase salary to high]
D --> G[Give promotion]
E --> H[16.8%]
F --> I[4.7%]
G --> J[<25.4%]
Extensions: Interaction Effects & Scenario Forecasting
- Interaction between salary level and department can reveal differential effects (e.g., a salary hike may retain HR staff more than management).
- This method is called scenario forecasting — the organisation tests multiple hypothetical changes and picks the one that best reduces turnover risk.
Exam tip: When building logistic models with categorical predictors, always create ( k-1 ) dummies. The baseline category (e.g., “low salary”) is absorbed into the intercept. Changing a dummy to 1 shifts the log‑odds relative to that baseline.
Key takeaways
- Categorical variables enter logistic regression as dummy variables (baseline omitted).
- Coefficients on dummies represent change in log‑odds compared to the baseline category.
- In the worked HR example: low → medium salary cut quit probability from 25.4% to 16.8%; low → high cut it to 4.7%.
- Satisfaction and promotion have large negative effects; years at company increases leaving propensity.
- Once key factors (salary, satisfaction, promotion) are controlled, variables like work hours and evaluation ratings lose predictive power.
- Use the fitted model for scenario forecasting: change one predictor at a time and compute the new probability to guide decisions.
The Curse of Dummy Variables
Fixed effects and interaction effects quickly explode the number of features. In the employee‑retention example:
- Salary – 3 categories → 2 dummy variables
- Department – 10 categories → 9 dummy variables
- Salary × Department interaction – 30 unique combinations → 29 dummy variables
Total: over 30 dummy columns. Estimation becomes unstable, convergence may fail, and interpretation suffers.
| Source | Categories | Dummy variables needed |
|---|---|---|
| Salary (fixed) | 3 | 2 |
| Department (fixed) | 10 | 9 |
| Salary × Department (interaction) | 30 | 29 |
| Total | ≥ 30 |
One partial remedy: drop interaction terms for categories with very few observations (e.g., if a department has only low‑salary employees, ignore the other salary‑department combos). But even then the model may stay too complex.
Exam tip: Whenever a categorical feature has many levels, or you include interactions, always check the total dummy count. A model with >20–30 dummy variables on a modest dataset is a red flag for overfitting and non‑convergence.
Why Variable Selection Matters
Variable selection is the process of identifying the subset of features that are most important for predicting the outcome, keeping the model simple without sacrificing predictive or explanatory power.
Three core reasons:
- Avoid overfitting – Adding more features always inflates (or pseudo‑), eventually approaching 1 on training data. But an close to 1 signals that the model fits noise, not signal – it will generalise poorly to new data.
- Interpretability – A model with 5–10 coefficients is far easier to understand than one with 50.
- Computational efficiency – Fewer variables means faster training and lower memory use.
Forward Selection
Start with an empty model (only the intercept). At each step:
- Test every candidate variable not yet in the model.
- Add the one that most improves model fit (e.g., highest increase).
- Use an F‑test (or deviance test in logistic regression) to check whether the improvement is significant.
- Repeat until no remaining variable yields a significant improvement.
flowchart LR
A[Empty model: intercept only] --> B{Test each candidate}
B --> C[Add variable with best improvement]
C --> D{Significant?}
D -->|Yes| B
D -->|No| E[Stop, keep current model]
Backward Elimination
Start with the full model (all variables). At each step:
- Identify the least important variable (e.g., highest ‑value, smallest drop if removed).
- Remove it.
- Repeat until removing any remaining variable significantly hurts model fit.
flowchart LR
A[Full model: all variables] --> B{Find least important}
B --> C[Remove it]
C --> D{Removal harms model?}
D -->|No| B
D -->|Yes| E[Stop, keep current model]
Stepwise Selection
A hybrid that combines forward and backward:
- Begin like forward selection: add the best variable.
- At every step, re‑evaluate all previously included variables. If any has become non‑significant (because the new variable took over its role), remove it.
- Continue until no variable can be added and none needs removal.
This handles the problem that some variables matter only in the presence of others – a variable that was significant at step 2 may become redundant after a later addition.
Ad‑hoc P‑Value Approach
A simpler, more manual method:
- Fit the full model once.
- Examine the ‑values of each coefficient.
- Remove all variables with non‑significant ‑values.
- (Optional) Refit and re‑check – significance can shift when variables are removed.
Caution: Because coefficients interact, a variable may appear non‑significant in the full model but become significant after dropping a correlated predictor. Always re‑evaluate after pruning.
Exam tip: The ad‑hoc p‑value method is fast but risky. It is acceptable only when you verify stability by fitting a few reduced models. The stepwise approach is more robust because it continuously checks for both additions and removals.
Key Takeaways
- Fixed/interaction effects with many categories generate dozens of dummy variables, causing overfitting, convergence issues, and poor interpretability.
- Variable selection finds a balance between model simplicity and accuracy.
- Common approaches: forward selection (add one by one), backward elimination (remove one by one), stepwise selection (add then re‑check removals), and ad‑hoc p‑value (prune non‑significant predictors).
- Always watch for overfitting: more features inflate , but hurt generalisation.
- In practice, use software‑built routines; but understand the logic to set sensible stopping criteria (e.g., significance level for entry/removal).
Non-Linear Regression Model
Non-linear regression models relationships where the change in the dependent variable is not proportional to the change in the independent variable. Unlike linear regression, it can capture curved, S‑shaped, or saturating patterns. This flexibility is essential for many real-world business problems where the underlying dynamics are inherently complex.
Why non‑linear? Common business applications
- Advertising & sales – Early ad spend may boost sales sharply, but additional spend eventually yields diminishing returns. Non‑linear models capture this plateau.
- Pricing & demand – Lowering price may initially spike demand, but further cuts produce only marginal gains. Complex price–response curves are better fitted with non‑linear terms.
- Growth models – Revenue or product adoption often follows an S‑shaped (sigmoid) pattern: rapid early growth, then slowdown as market saturates.
- Manufacturing & cost – Output costs may fall due to economies of scale, then rise again from inefficiencies. A non‑linear model can identify the optimal production level.
Key non‑linear regression methods
Polynomial regression
Generalizes linear regression by adding higher‑degree terms of the predictor(s). A quadratic (2nd‑degree) model with one predictor is:
Adding a cubic term () yields a cubic polynomial.
When to use – When the dependent variable rises/falls sharply at certain points and flattens elsewhere (e.g., product demand vs. price).
Caution – Higher degrees increase complexity and risk overfitting; quadratic or cubic usually suffice.
Exponential regression
Models rapid acceleration (or deceleration) where the dependent variable changes at a rate proportional to its current value:
When to use – Viral campaign spread, rumor propagation, or any scenario where growth accelerates quickly.
Logarithmic regression
Models quick initial growth that then levels off – the mirror of exponential:
When to use – Situations with diminishing returns, e.g., advertising spend vs. brand awareness.
Power regression
Models a relationship where the rate of change in is a constant proportion of the change in :
When to use – Production efficiency vs. units produced (efficiency improves at a decreasing rate as scale increases).
Logistic regression (non‑linear form)
Uses the sigmoid (logistic) function to produce an S‑shaped curve:
(Here can be a continuous proportion or a binary probability.)
When to use – New product adoption, market penetration, or any process that saturates.
Choosing the right method
flowchart TD
A[Observe pattern of relationship] --> B{Is it linear?}
B -->|Yes| C[Use linear regression]
B -->|No| D[Identify shape]
D -->|Diminishing returns, levels off| E[Logarithmic]
D -->|Rapid acceleration / deceleration| F[Exponential]
D -->|S‑shaped / saturation| G[Logistic]
D -->|Parabolic / curved peak or trough| H[Polynomial (quadratic/cubic)]
D -->|Constant proportional rate| I[Power]
Comparison of methods
| Method | Pattern captured | Typical equation | Example use |
|---|---|---|---|
| Polynomial (quadratic) | Curved, single bend | Price vs. demand | |
| Exponential | Rapid growth/decay | Viral campaign spread | |
| Logarithmic | Fast initial growth, then flattening | Ad spend vs. sales | |
| Power | Constant proportion rate change | Production efficiency scaling | |
| Logistic | S‑shaped saturation | Product adoption |
Exam tip – Overfitting is a real danger with polynomial regression. Stick to quadratic or cubic unless domain knowledge strongly suggests a higher degree. Cross‑validate to check generalisability.
Key takeaways
- Non‑linear regression models curved, non‑proportional relationships between variables.
- Common methods: polynomial (parabolic), exponential (rapid change), logarithmic (diminishing returns), power (constant proportion), logistic (S‑shaped).
- Choice depends on the observed pattern in the data – mis‑specification leads to poor predictions.
- Applications include advertising response, pricing optimisation, growth modelling, and manufacturing cost analysis.
- Higher‑degree polynomials increase flexibility but also the risk of overfitting; keep models as simple as the data allow.
Case Study: Bangalore House Prices
A case study integrating nonlinear regression and categorical-variable techniques to model house prices in Bangalore. The dataset contains 4340 rows and 10 variables.
Data Overview
| Variable | Type | Description |
|---|---|---|
posted_by | Categorical | Owner, dealer, or builder |
RERA_approval | Binary | 1 if approved, 0 otherwise |
bedrooms | Numeric | Number of bedrooms |
total_sqft | Numeric | Total area in square feet |
ready_to_move | Binary | 1 if ready to occupy, 0 otherwise |
resale | Binary | 1 if resale property, 0 otherwise |
address | Categorical (high-level) | General location |
longitude | Numeric | Longitude coordinate |
latitude | Numeric | Latitude coordinate |
price | Numeric (lakhs of ₹) | House price |
The response variable of interest is price, but due to its relationship with area and skewness, a transformation is needed.
Five Key Questions
The case study builds toward one main question through four preparatory ones:
- How is price distributed across the city? (exploratory mapping)
- Does price depend on specific streets/areas? (pattern identification)
- Is the price distribution normal? (normality check for regression)
- Does price differ by who posted (builder, owner, dealer)?
- What factors impact price, and how? (main modelling question)
These questions are cumulative: Q1–Q4 inform the model specification for Q5.
Exploratory Data Analysis (EDA)
Price Distribution and Normality
A histogram of price shows positive skew: high frequency at low prices, a sharp drop, then a long right tail with few observations. The distribution is clearly not normal.
Plotting price per square foot () reduces the effect of area but still shows positive skew – not symmetric.
Exam tip: In real data, variables like price, income, and rent almost always exhibit positive skew. The standard remedy is a log transformation.
Applying yields a near-symmetric histogram (some outliers on the left remain). Visually, the normality assumption becomes plausible. Formal confirmation would require a chi-square goodness-of-fit test.
Why Price per Sq Ft and Log Transformation
- Price per sq ft is the relevant metric for buyers because total price is proportional to area. A buyer compares cost per unit area.
- Log transformation is the appropriate fix for positive skew. It stabilises variance and makes the distribution more symmetric – both important for regression assumptions.
Nonlinear Regression Model
Model Specification
The regression is nonlinear because the response variable is transformed:
Independent variables (predictors):
RERA_approval(binary)bedrooms(numeric – initially treated as continuous)ready_to_move(binary)resale(binary)total_sqft(numeric)posted_by(categorical: owner, dealer, builder) – converted to dummy variables with builder as the baseline
This is a log-linear model: response is log-transformed, predictors remain untransformed.
Results and Interpretation
| Predictor | Sign | Significance (5% level) | Interpretation |
|---|---|---|---|
RERA_approval | Positive | Significant | Approval increases price per sq ft |
bedrooms | Positive | Significant | More bedrooms → higher price per sq ft (holding area fixed) |
total_sqft | Negative | Significant | Larger area → lower price per sq ft (economies of scale) |
ready_to_move | — | Not significant | No price premium for readiness |
resale | — | Not significant | Resale properties do not sell at a discount or premium |
posted_by = owner | Positive | Significant | Higher price per sq ft than builder |
posted_by = dealer | Positive (larger) | Significant | Even higher premium over builder |
Exam tip: In a log-linear model, coefficients on binary predictors represent the expected change in ; exponentiate to get the multiplicative effect on (e.g., gives the factor change in price per sq ft).
Because the dependent variable is logged, each coefficient indicates the change in for a one-unit increase in the predictor. For posted_by, both owner and dealer command a premium relative to builder, with dealer being the costliest.
Model Improvements and Further Analysis
The lecture identifies several ways to upgrade the model:
- Log-log model: Transform both response and
total_sqft– i.e., model as a function of . This captures proportional relationships better. - Bedrooms as categorical: The price increment per additional bedroom is likely nonlinear. Treating bedrooms as a categorical variable (1BR, 2BR, 3BR+) or applying a transformation (log, square root) may improve fit.
- Interaction effects:
resaleandposted_bymay interact – an owner selling a resale property might have different pricing than a builder selling a new one. - Location effect: Address/lat–lon data introduces many categories. Smart encoding (e.g., clustering neighbourhoods, using spatial coordinates, or creating a distance-from-center variable) is needed to avoid an explosion of dummy variables.
- Cross-validation for prediction: To compare models on predictive performance (not just ), split the data (e.g., 4000 training, 340 test). Train on one part, predict the other, and evaluate accuracy. This concept is explored further in the next module on time series and predictive modelling.
Key takeaways
- The case study demonstrates a complete workflow: EDA → transformation → nonlinear regression → interpretation → refinement.
- Log transformation is essential for right-skewed price data; log-linear models are a standard nonlinear regression tool.
- Categorical predictors require dummy variables; interpretation of coefficients changes when the response is logged.
- Model improvement avenues include log-log form, categorical treatment of numeric variables, interactions, and spatial effects.
- Cross-validation separates model fitting from evaluation – critical for predictive modelling.
Linear Regression Recap
Linear regression models the relationship between a continuous dependent variable and one or more independent variables. The goal is to quantify the strength and direction of these relationships: how changes in a predictor translate into increases or decreases in the outcome.
Because of its simplicity and interpretability, linear regression is widely used when the relationship between variables can be assumed linear. For example, a company can model the relationship between various factors (salary, workload, work environment) and employee satisfaction to identify what keeps employees happy.
Exam tip: Linear regression predicts a continuous outcome. The coefficients are directly interpretable: a one-unit increase in is associated with a change in , holding other predictors constant.
Key takeaways
- Linear regression models continuous dependent variables.
- Assumes a straight-line relationship.
- Provides clear, actionable insights in business contexts.
- Example: employee satisfaction analysis.
Logistic Regression Recap
Logistic regression is used when the dependent variable is binary (two possible outcomes). It models the probability of an event occurring, ensuring predicted values fall between 0 and 1.
Unlike linear regression, logistic regression uses the logit link function:
where is the probability of the event.
Business applications
- Employee attrition: Predict likelihood of an employee leaving based on job satisfaction, salary, workload, tenure. Enables proactive retention (promotions, salary increases, development).
- Customer segmentation & marketing: Predict whether a customer will purchase based on browsing behavior, purchase history, demographics. Helps target campaigns.
- Credit scoring & risk management: Predict probability of loan default using credit history, income, employment status. Informs approval/denial decisions.
Key takeaways
- Logistic regression for binary outcomes (0/1).
- Predicted values are probabilities bounded by 0 and 1.
- Used in HR analytics, marketing, financial risk.
Non‑Linear Regression Recap
Non‑linear regression is needed when the relationship between variables cannot be adequately captured by a straight line. Many real‑world business situations show curved patterns.
Example: House price analysis – the dependent variable (price) may not be normally distributed. Applying a logarithmic transformation (e.g., ) creates a non‑linear model that often improves performance.
Common scenarios
- Diminishing returns in marketing: Sales increase with ad spend, but after a point each additional dollar yields smaller sales increments. Non‑linear models capture this saturation effect, helping allocate budgets efficiently.
- Demand forecasting: The relationship between price and demand often follows a curve – small price changes may have large effects on demand in some ranges, little effect in others.
Exam tip: Non‑linear does not necessarily mean “complicated.” A log transformation of either the dependent or independent variable is a simple form of non‑linear regression that can linearise a curved relationship.
Key takeaways
- Non‑linear regression for curved relationships.
- Logarithmic transformations are a common tool.
- Business examples: marketing diminishing returns, price–demand curves.
Categorical predictors
Many business variables are categorical – gender, region, product type. These are incorporated into linear, logistic, or non‑linear regression using dummy variables (0/1 coding). This allows comparison of the impact of different categories on the outcome.
Interaction effects
Interaction effects occur when the relationship between one independent variable and the dependent variable changes depending on the value of another independent variable. For example:
- The effect of advertising on sales may depend on the pricing strategy.
- The impact of employee training on performance may vary by department.
Interaction terms are added to the regression model, often as the product of the involved variables (e.g., ). Including them leads to a more precise model that captures how combinations of factors influence outcomes.
flowchart LR
A[Factor 1] --> C[Outcome]
B[Factor 2] --> C
A -.->|moderates| B
B -.->|moderates| A
A & B --> D[Interaction Term]
D --> C
Key takeaways
- Dummy variables enable categorical predictors in regression.
- Interaction effects capture dependency between predictors.
- Including interactions improves model accuracy for business decisions (e.g., attrition, house prices).
Non - Parametric Methods
Parametric and Nonparametric Methods
Statistical methods answer questions about populations using sample data: summarizing, testing relationships, making predictions. The choice between parametric and nonparametric methods depends entirely on what we assume about the underlying data distribution.
What is a parametric method?
The term comes from parameters — numbers that summarize a population (e.g., population mean , population proportion , population variance ). Parametric methods assume the data follow a specific probability distribution completely defined by these parameters.
- Example: Binary data → Bernoulli distribution, defined by .
- Example: Continuous data → Normal distribution, defined by and .
Key idea: Parametric methods require a “blueprint” — the data must come from a known distribution (e.g., normality for a -test). When the assumption holds, these methods are efficient and powerful.
What is a nonparametric method?
Nonparametric methods make no assumption about the underlying distribution. They are also called distribution-free methods. They work with ranks, relative positions, or counts rather than raw values and parameters.
- Data can be skewed, multimodal, have outliers — nonparametric methods remain valid.
- They are more flexible and robust when assumptions fail.
Core problems addressed by nonparametric methods in this module
- Independence between two variables (e.g., product type vs. satisfaction).
- Goodness of fit — does the data follow a specified distribution?
- Two-sample distribution comparison — do two samples come from the same distribution?
Worked example: Customer satisfaction scores (Product A vs. Product B)
A company collects satisfaction scores (1–10) for two products. The goal: determine whether a significant difference exists.
Parametric approach (two-sample -test)
- Null hypothesis: (population means equal).
- Alternative: .
- Assumptions: scores are normally distributed in both groups; often equal variances assumed.
- Output: estimate of mean difference, -value, confidence interval.
Nonparametric approach (Mann‑Whitney U test / Wilcoxon rank sum test)
- Null hypothesis: No difference in the distribution of scores between groups.
- Alternative: distributions differ.
- Method: Ranks all observations together; uses relative ranks to compute test statistic.
- No normality assumption; robust to skewness, outliers, bimodality.
- Output: a -value indicating whether one group tends to have higher/lower scores, but no direct estimate of effect size (e.g., mean difference).
Comparison: parametric vs. nonparametric
| Aspect | Parametric | Nonparametric |
|---|---|---|
| Assumptions | Data follows a specific distribution (e.g., normal) | None (distribution‑free) |
| Parameters estimated | , etc. | Not directly; uses ranks |
| Efficiency (given assumptions hold) | High – fewer data needed, more powerful | Lower – larger samples needed for same precision |
| Robustness to violations | Low – results can be misleading | High – valid even with skewness, outliers |
| Interpretation | Direct: mean difference, regression coefficients | Indirect: only direction or existence of difference |
| Example test | Two‑sample -test | Mann‑Whitney U test |
flowchart TD
A[Data collected] --> B{Can we assume normality?}
B -->|Yes| C[Use parametric method - e.g., t-test]
B -->|No / Unsure| D[Use nonparametric - e.g., Wilcoxon rank sum test]
C --> E{Check assumptions?}
E -->|Violated| D
Exam tip: Parametric tests are more powerful only when their assumptions are met. If data is skewed or has outliers, a nonparametric test is the safer choice — it may require a larger sample but avoids invalid conclusions.
Advantages and disadvantages
Parametric
- ✅ Simpler, fewer parameters to estimate.
- ✅ Powerful and precise when assumptions hold.
- ❌ Results can be completely wrong if assumptions violated.
Nonparametric
- ✅ Flexible, works with any distribution.
- ✅ Robust to outliers and skewed data.
- ❌ Requires larger sample sizes for equivalent power.
- ❌ Provides less detailed inference (e.g., no mean difference).
Practical workflow
- Start with parametric methods if assumptions seem reasonable.
- Always check assumptions (e.g., using goodness‑of‑fit tests, Q‑Q plots).
- If assumptions are violated, switch to a nonparametric alternative.
Key takeaways
- Parametric methods assume a known distribution (e.g., normal) and estimate population parameters.
- Nonparametric methods (distribution‑free) use ranks or counts and require no distributional assumption.
- Same goal — hypothesis testing or inference — but different trade‑offs: efficiency vs. robustness.
- The Mann‑Whitney U test is the nonparametric counterpart to the two‑sample -test.
- Nonparametric tests often cannot quantify effect size beyond “different or not”.
Intuition and Definition
Independence between two events means the occurrence or non‑occurrence of one does not influence the occurrence of the other. Intuitively: knowing whether one event happened gives zero information about whether the other happened.
Example: Tossing two coins — the outcome of the first toss tells you nothing about the outcome of the second.
Formal definition – events and are independent iff
This is the multiplication rule for independent events. If the equality holds, the chance that both events occur is simply the product of their individual probabilities; no “adjustment” for influence.
Business Example: Shoe and Phone Case
Retail manager analyzing shopping behaviour:
- Event A: customer buys a particular brand of shoes
- Event B: customer buys a mobile phone case
Suppose and .
If the two purchases are independent, then
i.e., about 6% of customers would buy both.
Dependence can be positive or negative:
- Positive: customers who buy shoes are more likely to buy socks →
- Negative: customers who buy shoes are less likely to buy slippers →
For any two dependent events, the multiplication rule does not hold.
Dependent Events: Age and Gaming Console
- Event A: customer aged 18‑25
- Event B: customer purchases a gaming console
Intuition says younger people are more likely to buy a console → the events are dependent.
In this case:
A larger joint probability than the independence assumption would predict.
Independent Random Variables
Independence extends naturally to random variables and :
and are independent iff for every pair of values ,
Knowing the value of gives no information about (and vice versa).
Business context – an online platform tracks two variables per customer per month:
- = number of digital products purchased
- = number of physical goods purchased
If and are independent, marketing strategies for digital and physical products can be developed separately.
Testing Independence with Data: Toy Example
The company samples 100 customers and observes:
Marginal distribution of (digital products):
| Frequency | ||
|---|---|---|
| 0 | 10 | 0.10 |
| 1 | 50 | 0.50 |
| 2 | 30 | 0.30 |
| 3 | 10 | 0.10 |
| Sum | 100 | 1.00 |
Marginal distribution of (physical goods):
| Frequency | ||
|---|---|---|
| 0 | 5 | 0.05 |
| 1 | 40 | 0.40 |
| 2 | 40 | 0.40 |
| 3 | 15 | 0.15 |
| Sum | 100 | 1.00 |
If and are independent, the expected joint probability for any combination is the product of the marginals:
- → expected 0.5 customers
- → expected 20 customers
Similarly, the full independence‑implied joint distribution would be computed for all pairs.
Key insight: In real data, even when independence holds, the observed counts will never exactly match the products due to sampling variability. A non‑parametric test (e.g., chi‑square test of independence) determines whether the deviation is statistically significant or just random noise.
In the toy example, we expect 0.5 customers with , but we could observe 1 or 0. If observed = 1, the difference is small relative to sampling error; if observed = 10, it would strongly suggest dependence.
The goal: detect whether, for all ,
“Approximately” because sampling variation is accounted for.
Key takeaways
- Independence means ; knowing one event gives no info about the other.
- For random variables: equality of joint and product of marginals must hold for all values.
- Dependence can be positive (increases joint probability) or negative (decreases it).
- In practice, we compare observed joint frequencies to the product of marginal frequencies; sampling variability prevents exact match.
- A non‑parametric method (covered next) tests whether the gap is statistically significant.
Chi-square Test of Independence
A chi-square test of independence determines whether two categorical variables are associated. Intuitively, if the variables are independent, the observed pattern in a contingency table should match what we expect by chance; large mismatches signal dependence.
Hypotheses
- Null : The two variables are independent.
- Alternative : The two variables are not independent (dependent).
Contingency Table (Observed Frequencies)
Data are arranged in an table, where = number of rows (categories of variable 1) and = number of columns (categories of variable 2). Each cell contains the observed frequency .
Expected Frequencies
Under , the expected frequency for cell is derived from the multiplication rule of probability:
Test Statistic
The chi-square test statistic measures total squared deviation between observed and expected, standardized by expected:
Degrees of Freedom
Under , follows a chi-square distribution with:
Decision via p-value
Compute the p-value = . If p-value (commonly 0.05), reject and conclude the variables are dependent.
Worked Example: Bloomberg Businessweek
A survey asked business travelers about the type of ticket (first class, business class, economy) and trip type (domestic, international).
Observed frequencies (partial):
| Ticket type | Domestic | International | Row total |
|---|---|---|---|
| First class | 29 | 22 | 51 |
| Others (business, economy) | not specified | not specified | (remainder) |
| Column total | 642 | ? | n = 920 |
(Only the first‑class row was explicitly given; the domestic column total is 642.)
Expected frequency for first class / domestic under independence:
Contribution of this cell to :
Summing over all six cells gives:
Degrees of freedom: .
p-value: Using Excel’s CHISQ.DIST.RT(100.43, 2), the p-value is approximately (essentially 0).
Conclusion: Since p-value , reject . The type of ticket purchased is not independent of the type of trip; a significant association exists.
flowchart LR
A[Observed & Expected frequencies] --> B[Compute χ² = Σ (O-E)²/E]
B --> C[Compare to χ² distribution with df = (r-1)(c-1)]
C --> D{p-value < α?}
D -->|Yes| E[Reject H₀: variables are dependent]
D -->|No| F[Fail to reject H₀: no evidence of dependence]
Exam tip: The test requires that expected frequencies are at least 5 for most cells (commonly 80% of cells). If violated, combine categories or use Fisher’s exact test. The test only detects existence of association, not strength or direction.
Key takeaways
- Chi-square test of independence assesses association between two categorical variables.
- : independence; : dependence.
- Expected frequency per cell = (row total × column total) / grand total.
- Test statistic: .
- Degrees of freedom = .
- A small p-value (e.g., < 0.05) leads to rejection of independence.
Chi-Square Test of Independence (Categorical Variables)
The chi-square test of independence determines whether two categorical variables are related or independent. Intuitively, if the variables are independent, the distribution of one variable should look roughly the same across all levels of the other variable. If they are dependent, some categories will have systematically different proportions.
Example: Department vs. Salary in an HR Dataset
- Dataset: 14,999 employees, 10 variables. Focus on two categorical variables:
- Department (10 categories): Sales, Accounting, HR, Technical, Support, Management, IT, Product Management, Marketing, R&D.
- Salary (3 categories): Low, Medium, High.
- Research question: Is salary independent of department? (Equivalently: Does salary distribution vary across departments?)
Hypotheses
- : Department and salary are independent.
- : Department and salary are not independent (i.e., there is an association).
Steps of the Test
Step 1 – Contingency Table of Observed Frequencies
Create a two-way table using COUNTIFS in Excel. Rows = departments, columns = salary levels.
| Department | Low | Medium | High | Row total |
|---|---|---|---|---|
| Sales | 2099 | ... | ... | 7316 |
| Accounting | 358 | ... | ... | ... |
| HR | ... | ... | ... | ... |
| Technical | ... | ... | ... | ... |
| Support | ... | ... | ... | ... |
| Management | ... | ... | ... | ... |
| IT | ... | ... | ... | ... |
| Product Mgmt | ... | ... | ... | ... |
| Marketing | ... | ... | ... | ... |
| R&D | ... | ... | ... | ... |
| Column total | 4140 | ... | ... | 14999 |
(Exact counts not fully listed in the lecture; the computed χ² uses full 30-cell table.)
Step 2 – Expected Frequencies under
Under independence, the expected count for cell is:
Example for Sales × Low:
Compute all expected frequencies; verify that row and column totals match the observed marginals.
Step 3 – Chi-Square Test Statistic
For Sales × Low:
Summing over all 30 cells yields:
Step 4 – Degrees of Freedom
Step 5 – p-value
The p-value is the right-tail probability of obtaining a value at least as extreme as 700.92 under a distribution.
In Excel: =CHISQ.DIST.RT(700.92, 18) → (essentially zero).
Step 6 – Conclusion
Since the p-value is far below any common significance level (e.g., 0.05), we reject . There is strong evidence that salary and department are not independent – salary distributions differ across departments.
Understanding which categories drive the association
The largest contributions to come from the Management department:
- Deviations: (3 values) sum to ≈ 636.77 out of 700.92.
- This suggests that Management’s salary pattern is markedly different from the average.
Further analysis could test independence after removing Management (or Management, Sales, HR, Support) to see if the remaining departments show independence.
flowchart TD
A[State H₀: Independence] --> B[Build contingency table of observed counts]
B --> C[Compute expected counts under H₀]
C --> D[Calculate χ² statistic]
D --> E[Find degrees of freedom (r-1)(c-1)]
E --> F[Obtain p-value (right-tail)]
F --> G{ p < α? }
G -->|Yes| H[Reject H₀ → Variables are dependent]
G -->|No| I[Fail to reject H₀ → No evidence of association]
Exam tip: The chi-square test only tells you whether there is an association, not how strong it is. Large cell contributions (like Management’s) can hint at which categories differ, but follow-up tests are needed to confirm.
Key Takeaways
- The chi-square test of independence compares observed frequencies to expected frequencies under independence.
- Expected frequencies are calculated using the product of marginal totals divided by the total sample size.
- Test statistic: .
- Degrees of freedom = .
- A very small p-value leads to rejection of independence.
- The test is non-parametric – it makes no distributional assumptions about the underlying population, only that the data are counts.
Chi-Square Test of Independence for Continuous Variables
Pearson’s correlation coefficient measures linear association between two numerical variables, but it has two critical limitations:
- Normality assumption – conventional inference requires the data to be normally distributed, a condition often violated in practice.
- Linear focus only – it cannot capture non‑linear relationships. Two variables may be strongly dependent yet have near‑zero correlation.
The chi‑square test of independence overcomes both problems when applied to continuous data. It requires no distributional assumptions, detects any form of association (linear or non‑linear), and is robust to data quality issues (e.g., outliers, entry errors).
How it works: discretize then test
The core idea is to convert continuous variables into categorical bins (discretize), then apply the standard chi‑square test of independence on the resulting contingency table.
Example: Satisfaction vs. Average Monthly Hours (HR dataset)
- Satisfaction level (continuous, 0–1) → discretised into 5 bins:
[0,0.2),[0.2,0.4),[0.4,0.6),[0.6,0.8),[0.8,1]. - Average monthly hours (continuous, 96–310) → discretised into 4 bins:
≤150,(150,200],(200,250],>250.
These choices are a judgment call – guided by descriptive statistics (range, mean, median).
Rules of thumb:
- Not too few or too many bins.
- Each cell of the table should have sufficient (≥5) observations; avoid highly disproportionate counts.
The discretised data produce a joint frequency table (rows = satisfaction bins, columns = hours bins):
| Satisfaction \ Hours | ≤150 | 150–200 | 200–250 | >250 | Row total |
|---|---|---|---|---|---|
| [0.0 – 0.2) | ... | ... | ... | ... | ... |
| [0.2 – 0.4) | ... | ... | ... | ... | ... |
| [0.4 – 0.6) | ... | ... | ... | ... | ... |
| [0.6 – 0.8) | ... | ... | ... | ... | ... |
| [0.8 – 1.0] | ... | ... | ... | ... | ... |
| Column total | ... | ... | ... | ... | N |
Exam tip: The chi‑square test is performed exactly as for categorical data – compute expected frequencies under independence, calculate and compare to the critical value with degrees of freedom.
Hypotheses
- : Satisfaction level is independent of levels of average monthly hours (i.e., the row and column categories are independent).
- : Satisfaction level is not independent of levels of average monthly hours (dependence exists).
Connection to Pearson correlation
In an ideal setting, the conclusions from the chi‑square test should align with the sign and strength of the Pearson correlation coefficient. For this dataset, the (linear) correlation between satisfaction and average monthly hours is mildly negative – employees who work more tend to be less satisfied. If the chi‑square test also rejects independence, it reinforces that conclusion. A discrepancy would suggest a non‑linear relationship that correlation missed.
| Aspect | Pearson correlation | Chi‑square test (discretised) |
|---|---|---|
| Assumptions | Bivariate normality | No distributional assumptions |
| Relationship detected | Linear only | Any form (linear or non‑linear) |
| Sensitivity to outliers | High | Low (after binning) |
| Output | (‑1 to +1) | + p‑value |
Key takeaways
- Discretise continuous variables into bins (judgment call based on range and sample size) and then apply the standard chi‑square test of independence.
- The test works without normality, captures non‑linear associations, and is robust to data quality issues.
- Interpret results in the context of the bins – dependence means that the distribution of one variable differs across categories of the other.
- Compare findings with the Pearson correlation to check for consistency and to identify possible non‑linearity.
Why Goodness of Fit?
Many standard parametric methods — the t‑test, ANOVA, linear regression — assume the data follow a particular distribution (most often the normal). Other common assumptions include the exponential distribution for product lifetimes or the Poisson distribution for count data (e.g., number of defects). Because the validity of these methods hinges on the assumption being true, an objective way to check it is essential. The goodness of fit test provides that check: it determines whether a sample of observed data matches a specified theoretical distribution.
Core Idea: Observed vs. Expected Frequencies
The test compares the observed frequencies (how often each outcome actually occurred in the sample) with the expected frequencies derived from the hypothesised distribution. The key question: are the deviations between observed and expected large enough to conclude the data does not follow the assumed distribution, or can they be attributed to random chance?
This logic is the same as that of the χ² test of independence (covered earlier in the module). Both tests use a chi‑square statistic to evaluate the gap between observed and expected counts.
Assumed distribution (e.g., normal, Poisson)
↓
Compute expected frequencies for each category
↓
Collect observed frequencies from the sample
↓
Test: Are deviations (observed – expected) significantly large?
↓
If yes → reject assumption | If no → data consistent with the distribution
Exam tip: The goodness of fit test is a nonparametric method — it makes no assumption about the distribution of the test statistic itself, only about the data being tested.
Common Distributions Tested in Business Contexts
| Variable type | Example distributions | Typical application |
|---|---|---|
| Discrete | Binomial, Poisson | Number of defects in a batch (Poisson); number of successes in trials (binomial) |
| Continuous | Normal, Exponential | Customer purchase amounts (normal); product lifetime (exponential) |
Selecting the correct distribution for a given business problem is a critical first step; the goodness of fit test then validates that choice.
Business Applications
The transcript details numerous real‑world uses. They all share the same pattern: an assumed distribution is embedded in a decision model, and the test confirms or rejects that assumption.
| Domain | Specific use | Distribution typically assumed |
|---|---|---|
| Marketing & consumer behaviour | Check if customers choose brands equally (uniform) or if preferences follow a normal distribution. | Uniform, normal |
| Retail & sales | Validate that product demand follows a seasonal or normal pattern; check if sales across store locations follow a similar distribution (identify outlier stores). | Normal, seasonal patterns |
| Product demand forecasting | Assess whether past sales conform to the distribution used for future forecasts. | Varies (e.g., normal, exponential) |
| Quality control | Test if number of defects follows a Poisson distribution (stable process); verify that product weights/dimensions match the expected distribution. | Poisson, normal |
| Risk management | Check whether actual default rates match the binomial or normal model used for credit pricing. | Binomial, normal |
| HR analytics | Evaluate if employee attrition matches historical turnover distribution to guide workforce planning. | Historical distribution (any) |
| Supply chain & inventory | Validate demand patterns for inventory policy decisions. | Various |
Why It Matters
Goodness of fit tests act as a gatekeeper for downstream analytics. If the distributional assumption is wrong, any conclusions drawn from parametric methods (confidence intervals, hypothesis tests, forecasts) may be unreliable. By confirming or rejecting the assumption, the test ensures that business decisions are based on accurate and trustworthy models.
Key takeaways
- Goodness of fit test checks whether observed data follows a specific theoretical distribution (normal, Poisson, exponential, etc.).
- It compares observed frequencies to expected frequencies from the hypothesised distribution.
- The test is nonparametric and conceptually similar to the χ² test of independence.
- Widely used across marketing, retail, quality control, risk management, HR analytics, and supply chain to validate assumptions.
- A significant result (large deviations) indicates the data does not match the assumed distribution; a non‑significant result means the data is consistent with it.
- Always first identify the appropriate distribution for the business context, then use the test to verify.
General Principles of Goodness of Fit Test
A goodness of fit test checks whether a sample of data follows a specified probability distribution. Intuitively: does the observed data "look like" it came from the assumed distribution (uniform, normal, Poisson, etc.), or is the difference too large to be chance? The test quantifies the discrepancy between what we expect under the hypothesis and what we observe in the sample, using the chi‑square distribution.
Procedure: step‑by‑step
flowchart TD
A[Define H₀ and H₁] --> B[Construct intervals / categories]
B --> C[Compute observed frequencies O_i]
C --> D[Compute expected frequencies E_i under H₀ using CDF]
D --> E[Calculate chi-square statistic: χ² = Σ (Oᵢ – Eᵢ)² / Eᵢ]
E --> F[Determine degrees of freedom df = k – 1 – m]
F --> G[Find p‑value from χ² distribution with df]
G --> H{Reject H₀?}
H -->|p‑value small| I[Conclude data does NOT follow assumed distribution]
H -->|p‑value large| J[Fail to reject H₀ – data consistent with distribution]
1. Formulate hypotheses
- Null hypothesis (): The data follow a specific distribution (e.g., uniform, normal, Poisson).
- Alternative hypothesis (): The data do not follow that distribution. (No claim about what other distribution holds.)
2. Build intervals (for continuous variables)
- Divide the range into bins or categories.
- Bins need not be equal in width, but expected frequencies should be balanced (neither too large nor too small). For uniform distributions, equal‑width bins are natural.
- Example: For satisfaction level (range 0–1), use 10 bins of width 0.1.
3. Obtain observed frequencies ()
Count how many sample observations fall into each bin.
4. Compute expected frequencies () under
- Use the cumulative distribution function (CDF) of the assumed distribution.
- For any bin, , where is the total sample size.
- For a uniform distribution: .
- For other distributions (normal, binomial, Poisson), you must first estimate the parameters from the data (e.g., for normal, for Poisson). Then use the CDF (e.g.,
NORM.DISTin Excel).
5. Calculate the chi‑square test statistic
A larger value indicates greater deviation from .
6. Degrees of freedom (df)
- = number of intervals
- = number of parameters estimated from the data (e.g., 2 for normal, 0 for uniform, 1 for Poisson)
7. Decision
- Compute the p‑value using the chi‑square distribution with the appropriate df (e.g.,
CHISQ.DIST.RTin Excel). - If p‑value < significance level (typically 0.05), reject – the data do not fit the distribution.
Exam tip: The goodness of fit test only detects departure from ; it does not tell you what the true distribution is. Also, each estimated parameter reduces df by 1 – forgetting this is a common error.
Worked example: Testing uniform distribution of employee satisfaction
Data: Satisfaction level (0–1) of employees.
Hypotheses:
- : Satisfaction is uniformly distributed over [0,1].
- : Satisfaction is not uniformly distributed.
Step 2 – intervals: 10 equal‑width bins: [0,0.1], [0.1,0.2], …, [0.9,1.0].
Step 3 – observed frequencies ():
| Interval | Observed () |
|---|---|
| [0, 0.1) | 553 |
| [0.1, 0.2) | … |
| … | … |
| [0.9, 1.0] | … |
| Total | 14,999 |
(Only the first interval’s count is given in the lecture; the others sum to 14,999.)
Step 4 – expected frequencies: Under uniform distribution, each bin has probability 0.1, so
Step 5 – chi‑square statistic: The contribution for the first bin:
Summing over all 10 bins gives:
Step 6 – degrees of freedom: , (uniform requires no estimated parameters), so
Step 7 – p‑value: Using a chi‑square distribution with 9 df, the p‑value is effectively 0 (extremely small). Therefore, reject – satisfaction level is not uniformly distributed. The company should investigate factors (department, workload, etc.) driving this non‑uniform pattern.
Degrees of freedom – general rule (examples)
| Distribution | Parameters estimated () | Example with intervals |
|---|---|---|
| Uniform | 0 | |
| Normal | 2 () | |
| Poisson | 1 () | |
| Binomial | 1 () |
Exam tip: Always count how many parameters were estimated from the sample to compute the expected frequencies. This directly affects df and the critical value.
Key takeaways
- Goodness of fit tests whether sample data come from a specified distribution.
- Use the chi‑square statistic: , comparing observed vs. expected counts.
- For continuous distributions, bin the data and compute expected frequencies via the CDF.
- Degrees of freedom: (intervals minus parameters estimated).
- A very small p‑value rejects ; the data do not fit the assumed distribution.
- The test is widely applicable – uniform, normal, Poisson, binomial – but requires careful interval construction and parameter estimation.
Goodness of Fit Test for Poisson Distribution
Intuition: The Poisson distribution models the count of rare, independent events over a fixed interval (e.g., customer arrivals, equipment failures). A goodness of fit test checks whether observed frequency counts (e.g., number of projects per employee) plausibly come from a Poisson process. If the data fit, the events appear random and independent at a constant average rate. If not, systematic factors (e.g., uneven workload) may be present.
Application context: In the HR dataset (14,999 employees), the only integer-valued variable suitable for Poisson modelling is number of projects (satisfaction level is continuous; years/hours are continuous even if reported as integers). A goodness of fit test here informs whether project distribution is random — or whether some employees are overburdened.
Step-by-step procedure
1. Hypotheses
2. Observed frequencies
- Raw counts show zero employees with 0 or 1 projects, and none with >7.
- Cell merging (required to avoid zero expected frequencies): aggregate into six intervals.
- Final observed frequencies (after merging):
| Interval (projects) | Observed frequency |
|---|---|
| 2,388 | |
| (computed in Excel) | |
| (computed in Excel) | |
| (computed in Excel) | |
| (computed in Excel) | |
| (computed in Excel) | |
| Total | 14,999 |
Exam tip: Always merge cells so that no expected count is < 1 and at most 20% of cells have expected counts < 5. For Poisson, low-probability tails (0,1,7+) are typical candidates for merging.
3. Expected frequencies under
The Poisson probability mass function:
- Estimate using the sample mean: (from 14,999 observations).
- Compute probabilities for each merged interval using the Poisson distribution with .
- Multiply each probability by to get expected frequencies .
Example – first cell ( projects):
In Excel use:
POISSON.DIST(x, mean, cumulative)- For exact probability:
FALSE - For cumulative probability:
TRUE
- For exact probability:
- Last cell ():
Resulting table (partial):
| Interval | ||
|---|---|---|
| 2,388 | 4,025.79 | |
| ... | ... | |
| ... | ... | |
| ... | ... | |
| ... | ... | |
| ... | ... | |
| Total | 14,999 | 14,999.00 |
4. Chi-square test statistic
For this dataset, the sum of all six contributions yields:
5. Degrees of freedom and p-value
Using CHISQ.DIST.RT(2780.09, 4) in Excel gives a p-value ≈ 0 (extremely small).
6. Inference
Because the p-value is virtually zero, we reject . There is overwhelming evidence that the number of projects does not follow a Poisson distribution. The company should investigate why some employees are overburdened while others have too few projects.
Brief extension: Testing normality
The same logic applies to continuous variables. For a goodness of fit test for normality:
- : Data follow a normal distribution.
- Estimate both parameters: and from the sample.
- Create intervals (bins) over the continuous range.
- Compute expected frequencies using
NORM.DIST(x, mean, stdev, cumulative). - Calculate and compare to with .
Example variables from the HR dataset to test: satisfaction level, last evaluation, average monthly hours.
Key takeaways
- Goodness of fit tests whether observed frequencies match a specified theoretical distribution (Poisson, normal, etc.).
- For Poisson: estimate from the sample mean; merge low-frequency cells to satisfy expected count conditions.
- Degrees of freedom = (#cells) – 1 – (#estimated parameters).
- A very large (e.g., 2780 on 4 df) leads to rejection of the Poisson assumption.
- The same framework extends to any distribution (normal, binomial, etc.) by using the appropriate probability function.
- Real business use: validating randomness of events (arrivals, defects) or detecting systematic imbalances (workload, resource allocation).
Wilcoxon Signed Rank Test
The Wilcoxon signed rank test is a non‑parametric procedure that relies solely on the relative ordering (ranks) of observations rather than their raw values. Unlike a parametric t-test, it makes no assumption about the underlying distribution — making it ideal for small samples, skewed data, or when normality fails.
Core idea
- One‑sample: Are the data systematically higher or lower than a specified median?
- Two‑sample (paired): Is the median of the paired differences significantly different from zero?
The test ranks the absolute deviations (or differences) and then examines the signs of those deviations. If the positive deviations are consistently larger than the negative ones (or vice versa), the test infers a significant shift away from the hypothesised median.
When to use it
| Scenario | Parametric alternative | Why Wilcoxon wins |
|---|---|---|
| Small sample size, normality unclear | One‑sample t-test / paired t-test | No normality required; robust to outliers |
| Data heavily skewed (e.g., financial returns, delivery times) | Same | Ranks neutralise extreme values |
| Before‑after intervention (same subjects) | Paired t-test | Works even if effect magnitude is irregular |
| Matched pairs (treatment vs control) | Paired t-test | Handles unknown distribution of differences |
One‑sample signed rank test
Intuition: A company sets a target delivery time of 5 days. Observed times deviate above or below that target. The test checks whether the deviations are balanced around zero (i.e., typical delivery = target) or are systematically positive/negative (i.e., median delivery ≠ 5 days).
Procedure (conceptual – details follow in later lectures):
- Compute for each observation.
- Rank the absolute differences (ignore signs).
- Assign the original signs (+ or –) to the ranks.
- Sum the ranks of the positive differences () and negative differences ().
- Compare the smaller sum to a critical value.
Because ranks are used, a few extreme values do not dominate the result — the test focuses on the ordering of deviations.
Exam tip: The one‑sample signed rank test does not test the mean; it tests the median. This is a common source of confusion in exams.
Two‑sample (paired) signed rank test
When observations come in pairs — either from the same subject before/after, or from matched subjects (treatment vs control) — the test examines whether the median of the within‑pair differences is zero.
Example: A pharmaceutical company gives a drug to one group and a placebo to a matched control group. The paired difference (drug outcome – placebo outcome) is computed for each pair. If the drug has no effect, the differences should centre around zero. A signed rank test can detect if the median difference is significantly positive (drug better) or negative.
Business applications:
- Marketing: Compare sales before and after a campaign.
- Quality control: Product weight vs. a standard weight.
- Finance: Stock returns before vs. after a market event, or returns of two portfolios over the same period.
- Operations: Production efficiency before and after a process change.
Why it is attractive
- No distributional assumptions — works when a goodness‑of‑fit test rejects normality.
- Robust to outliers — ranks cap the influence of extreme values.
- Handles small samples — where parametric tests lose power or cannot be validated.
- Applicable to paired data — common in business experiments and A/B testing.
flowchart TD
A[Sample data available] --> B{Normality plausible?}
B -->|Yes, large sample| C[Use parametric t‑test]
B -->|No / small / skewed| D[Use Wilcoxon signed rank test]
D --> E{One sample?}
E -->|Compare to benchmark median| F[One‑sample signed rank]
E -->|Paired/matched observations| G[Two‑sample signed rank<br/>(paired differences)]
Key takeaways
- Wilcoxon signed rank test is a non‑parametric alternative to the one‑sample and paired t-tests.
- It tests the median (not mean) of differences from a hypothesised value or of paired differences.
- Ranks are based on absolute deviations; signs determine the direction of deviation.
- No normality assumption — safe for skewed data, small samples, and outlier‑prone data.
- Common in business for before/after comparisons, quality control, and financial analysis.
Wilcoxon Signed Rank Test – II
The Wilcoxon signed rank test (also called the one-sample Wilcoxon rank sum test) is a non-parametric procedure for determining whether the median of a single sample differs significantly from a hypothesized value . It is an alternative to the one-sample t-test when the normality assumption is violated or when the sample size is too small for parametric methods. Because the test works on ranks rather than raw values, it is robust to skewness and outliers.
Intuition: Instead of asking whether the mean differs from a target, we ask whether the typical observation (the median) is systematically higher or lower than a claimed value. By ranking the deviations and summing the ranks for positive deviations, we can detect a consistent directional shift.
When to use
- Data are not normally distributed (e.g., skewed, heavy tails).
- Sample size is very small (making normality check unreliable).
- Interest lies in the population median, not the mean.
- Presence of outliers would distort a t-test.
Test procedure
-
Compute differences: For each observation , calculate , where is the hypothesized median.
-
Rank absolute differences: Rank from smallest to largest (ignore sign). If ties occur, assign the average rank to tied values.
-
Assign signs: Attach the sign (+ or –) of to each rank. Ranks of zero differences () are discarded.
-
Sum positive signed ranks: Similarly, define as the sum of negative signed ranks. Always: where is the number of non‑zero differences.
-
Test statistic: For large samples (), use the z‑approximation: with Under the null hypothesis (population median ), has this known mean and standard error.
Exam tip: The approximation works because is the sum of independent (under equally likely +/–) signed ranks; by the Central Limit Theorem it becomes normal as grows.
For small samples (), exact critical values from the Wilcoxon signed rank distribution are used (not covered in this lecture).
-
Decision rule: Compare to a critical value from the standard normal distribution.
- At : reject if .
- At : reject if .
Alternatively, compute the p‑value:
using Excel
NORM.DISTor similar.
flowchart TD
A["Compute W⁺"] --> B["Calculate z = (W⁺ – μ) / σ"]
B --> C["|z| > critical value?"]
C -->|Yes| D["Reject H₀: median ≠ M₀"]
C -->|No| E["Fail to reject H₀"]
Worked example: Average monthly hours
Data: HR analytics dataset with employees.
Hypothesis: hours (a believed norm) vs. .
Steps:
- Differences: For employee 1, , so .
- Rank absolute differences: . Using
RANK.AVG, ties produce average ranks (e.g., 7134.5). - Signs: Negative differences get sign –1; positive get +1; exact 200 get 0 (discarded).
- Positive signed ranks: Extract ranks for all positive signs.
- : Sum of positive signed ranks = 57,539,873.
- Z‑score:
Decision:
- At , critical value = 1.96 → , reject . The median is significantly different from 200 hours.
- At , critical value = 2.58 → , fail to reject . The evidence is not strong enough at the 1% level.
Further exploration: Testing medians 199 and 201 yields:
- 199: significant evidence of deviation.
- 201: no evidence of deviation.
Thus the organization’s median lies between 200 and 201 hours.
Comparison with one‑sample t-test
The lecture suggests running a one‑sample t-test on the same data (testing mean = 200) and comparing results. Because the data likely violate normality, the t-test may give a different conclusion. Always accompany such tests with exploratory plots (e.g., histogram of monthly hours) to build a complete picture.
Exam tip: The Wilcoxon signed rank test is not a test of the mean; it is a test of the median. When the population is symmetric and normally distributed, the t-test is more powerful. When normality fails, the Wilcoxon test is more reliable.
Key takeaways
- The Wilcoxon signed rank test assesses whether the population median differs from a hypothesized value.
- It is a non‑parametric alternative to the one‑sample t-test, robust to non‑normality and outliers.
- Procedure: compute differences, rank absolute differences, assign signs, sum positive ranks ().
- For , use the z‑approximation: .
- Reject if exceeds the normal critical value (1.96 at 5%).
- Always report exploratory analysis (histograms, boxplots) alongside the test.
Paired Wilcoxon Signed‑Rank Test
The paired Wilcoxon signed‑rank test is a non‑parametric alternative to the paired t‑test. It answers: Is the median difference between two related samples significantly different from zero?
Use it when data come in pairs (same subject before/after, matched pairs) and the normality assumption fails.
Intuition
We don’t care about the absolute values of the two groups; we care only about the direction and magnitude of the difference within each pair. By ranking the absolute differences and then restoring the sign, we test whether positive and negative differences are balanced – if they are, the median difference is zero.
Hypothesis
For a two‑tailed test (is there any difference?):
- : median difference between paired observations = 0
- : median difference
For a one‑tailed test (e.g., did the campaign increase visits?), change to “median difference ” or “”.
Procedure
- Compute differences for each pair: .
- Ignore signs and rank the absolute values . Assign rank 1 to the smallest absolute difference; average ranks for ties.
- Restore signs to the ranks → signed ranks.
- Sum the positive ranks – denote this as .
- Under , should be close to half of total rank sum.
- Decision rule depends on sample size:
| Sample size | Method | Test statistic | Critical value source |
|---|---|---|---|
| Large‑sample normal approximation | Standard normal | ||
| Small‑sample exact table | Wilcoxon signed‑rank table (e.g., for , , critical = 8) |
Exam tip: The large‑sample formula uses the mean and variance . These come from the null distribution of signed ranks.
Worked Example (Marketing Campaign)
A company tracks website visits of 10 customers before and after a campaign.
Only the first four pairs are shown below (full data not given).
| Customer | Before | After | Difference | | Rank of | Signed rank | |----------|--------|-------|----------------|-------|----------------|-------------| | 1 | 50 | 55 | +5 | 5 | 4 | +4 | | 2 | 60 | 65 | +5 | 5 | 4 | +4 | | 3 | 45 | 48 | +3 | 3 | 2 | +2 | | 4 | 80 | 75 | –5 | 5 | 4 | –4 | | … | … | … | … | … | … | … |
Note: ties in absolute difference (e.g., three values of 5) receive average rank in a full ranking; this partial table uses a simplified rank for illustration.
Complete the ranking for all 10 customers, then compute = sum of positive signed ranks.
Result (per lecturer): For at (two‑tailed), the critical value from the Wilcoxon table is 8. The computed exceeds 8, so we reject – there is a statistically significant difference in website visits before vs. after the campaign.
Interpretation: The marketing campaign changed website traffic. To determine whether it increased visits, conduct a one‑tailed test (right‑tail: : median difference ).
When to Choose This Test
flowchart LR
A[Two related samples?] -->|Yes| B{Normality plausible?}
B -->|No| C[Paired t‑test]
B -->|Yes, but n is small <30| D[Paired Wilcoxon signed‑rank test]
B -->|Yes, n large| E[Paired t‑test acceptable]
C --> F[Safe]
D --> F
Key Takeaways
- Paired Wilcoxon signed‑rank test compares median difference in matched/paired data.
- Difference is computed; absolute values are ranked; signs restored; positive ranks summed → .
- For , use exact Wilcoxon table; for , use normal approximation .
- No normality assumption required – robust for small or skewed samples.
- The test tells you whether a difference exists; direction requires a one‑tailed version.
- Do not confuse with Wilcoxon rank‑sum test (for independent samples).
Summary of Module 1: Non-Parametric Methods
Non-parametric methods provide robust alternatives to parametric tests when underlying assumptions (e.g., normality, homoscedasticity) are violated. This module covered three core techniques: chi-square test of independence, goodness-of-fit test, and Wilcoxon signed-rank test. Each is widely applied in business for categorical data, distribution checks, and paired comparisons.
1. Chi-Square Test of Independence
Determines whether two categorical variables are associated. Intuition: If the variables are independent, the observed frequency of each combination should be close to what we’d expect by chance.
Test statistic:
where = observed count in cell , = expected count under independence .
Process:
- Build a contingency table of observed frequencies.
- Compute expected frequencies assuming no relationship.
- Calculate and compare to a critical value (degrees of freedom = ).
Example: A business wants to know if product type purchased is related to customer geographic region. A chi-square test on the contingency table of product × region can reveal regional preferences without any distributional assumptions.
Applications:
- Customer demographics, product categories, payment methods, satisfaction ratings.
- Can also be used as a non-parametric alternative to the correlation coefficient for continuous data (by discretizing into categories).
Key takeaways
- Only requires categorical data; no normality assumption.
- Tests independence between two variables.
- Calculated from observed vs. expected frequencies in a contingency table.
- Widely used in retail, marketing, healthcare, manufacturing.
2. Chi-Square Goodness-of-Fit Test
Assesses whether observed data follow a specific theoretical distribution (e.g., normal, Poisson). Intuition: Does the actual frequency distribution match the expected pattern?
Test statistic:
where = observed count in category , = expected count from the theoretical distribution.
Example:
- Retail sales forecasting: A company assumes customer spending follows a normal distribution. The test compares observed sales bins against normal expectations. If significant deviation is found, the forecasting model must be adjusted (better inventory, less waste/stockout).
- Quality control: Defects in manufacturing are expected to follow a Poisson distribution (constant average rate). The test verifies alignment; a significant result indicates a process shift.
Other applications:
- Finance: Check if stock returns follow a normal distribution (common in risk modeling).
- Marketing: Verify whether customer purchase patterns match expected distributions to fine-tune promotions.
Key takeaways
- Tests whether data match a specific distribution (normal, Poisson, etc.).
- Critical for validating assumptions behind forecasting, quality control, and risk models.
- Significant deviation prompts model adjustment or process investigation.
- Uses same formula as test of independence, but with one-way categories.
3. Wilcoxon Signed-Rank Test
A non-parametric alternative to the paired t-test (or one-sample t-test) when normality is not satisfied. It operates on ranks of the differences, making it robust to outliers and skewed data.
When to use:
- One sample vs. a hypothetical median.
- Two related (paired) samples: before/after, matched pairs.
Idea: Rank the absolute differences, then sum the ranks for positive and negative differences. The test statistic compares the smaller sum against a critical value.
Example: A company launches a new product feature and measures customer satisfaction for the same group before and after. Even if the satisfaction ratings are not normally distributed, the Wilcoxon test can reliably tell if the median difference is significant.
Business scenarios:
- Marketing campaign effectiveness – small sample, volatile sales figures.
- Employee productivity after a training program.
- Financial returns before/after an interest rate change – returns are often skewed with extreme outliers.
Advantages over paired t-test:
- No normality assumption required.
- Focuses on median difference rather than mean.
- Less influenced by extreme values.
Key takeaways
- Ranks differences between paired observations; does not require normality.
- Ideal for small samples, skewed data, or outliers.
- Use for one-sample or paired comparisons (before/after).
- Commonly applied in HR, marketing, and finance.
Why Non-Parametric Methods Matter
When assumptions like normality or homoscedasticity fail, these three tools offer reliable, assumption-light alternatives:
| Method | Data Type | Question Answered | Parametric Alternative |
|---|---|---|---|
| Chi-square independence | Categorical (two variables) | Are they related? | – (no direct param.) |
| Chi-square goodness-of-fit | Categorical (one variable vs. distribution) | Does the data fit a distribution? | – |
| Wilcoxon signed-rank | Paired continuous/ordinal | Is the median different? | Paired t-test |
Key takeaway for business analytics: Non-parametric methods handle real-world data (non‑normal, categorical, small samples) without sacrificing rigor. They enable confident decision‑making when parametric assumptions are untenable.
Predictive Analysis
Concept of Forecasting - Introduction
Forecasting is the process of making predictions about future events based on historical data and various statistical techniques. In business analytics, forecasting enables organizations to be proactive rather than reactive: by identifying patterns in past data, companies can anticipate demand, costs, revenue, customer behavior, and other critical variables subject to fluctuation.
Forecasting supports decision-making and strategic planning across all horizons. Common methods include regression models, time series analysis, machine learning algorithms, and econometric models. This module focuses specifically on regression models and time series analysis for forecasting.
Short‑Term vs. Long‑Term Forecasting
- Short‑term forecasting – e.g., predicting sales for the next week or month.
- Long‑term forecasting – e.g., projecting growth over several years or a decade.
Exam tip: The same method rarely performs well for both horizons. Short‑term forecasts often emphasize recent patterns; long‑term forecasts use broader trends and structural factors.
Applications of Forecasting in Business
| Application Area | Purpose | Example |
|---|---|---|
| Demand forecasting | Predict future product/service demand to align inventory with expected sales. | A retail store uses prior‑year sales, current trends, and customer purchasing behavior to avoid stockouts and overstocking. |
| Financial forecasting | Predict revenue, expenses, cash flow, and profit for budgeting and strategic planning. | A tech startup forecasts cash inflows/outflows to determine when it will achieve profitability and when additional capital may be needed. |
| Sales forecasting | Estimate future sales volumes to set revenue targets, allocate resources, and manage production. | A car dealership predicts seasonal demand for specific models (e.g., higher sales in summer) to stock appropriate quantities. |
| Workforce forecasting | Anticipate future staffing needs, especially for seasonal or growth‑driven fluctuations. | A hotel chain uses past booking data to hire adequate staff for the high‑tourist season. |
| Risk management forecasting | Identify potential risks and take preventive measures. | Banks use historical loan‑repayment data and credit scores to forecast the likelihood of loan defaults, improving lending decisions. |
| Fraud detection forecasting | Detect abnormal transaction patterns that may indicate fraud. | Credit‑card companies build models that flag transactions deviating from forecasted customer behavior. |
| Marketing / Customer churn forecasting | Predict customer behavior (e.g., likelihood of churn or purchase) to tailor retention and promotional efforts. | A streaming service (e.g., Hotstar) forecasts churn risk based on viewing habits and subscription tenure, then targets at‑risk customers with retention offers. |
Why Forecasting Is Critical
- Demand forecasting prevents both stockouts (lost sales, dissatisfied customers) and overstocking (tied‑up capital, storage costs).
- Financial forecasting helps allocate resources, manage cash flow, and communicate growth potential to investors.
- Sales forecasting guides production schedules, inventory levels, and sales force deployment.
- Workforce forecasting ensures adequate staffing during peak periods without over‑hiring.
- Risk forecasting minimizes losses (e.g., loan defaults) and maintains financial stability.
- Fraud detection protects both the institution and its customers from unauthorized activity.
- Customer behavior forecasting (e.g., churn, purchase likelihood) enables personalized marketing, improving conversion rates and customer experience.
Key takeaways
- Forecasting = making data‑driven predictions about future events using historical data and statistical techniques.
- Methods differ by horizon (short‑term vs. long‑term); one method rarely fits both.
- Major applications include demand, financial, sales, workforce, risk, fraud, and marketing forecasting.
- Accurate forecasts reduce uncertainty, optimize operations, and support proactive strategic planning.
- This module will cover regression‑based and time‑series forecasting techniques in depth.
Predictive Analysis of Continuous Data
Linear regression is the most common approach for identifying relationships between variables and is widely used for forecasting continuous data. It models the relationship between one or more independent variables (predictors) and a continuous response variable (dependent variable) by fitting a linear equation to the data. Once the model is trained, new values of the independent variables can be plugged in to predict future outcomes.
Example: A company forecasts monthly sales using advertising spend, product prices, and seasonal factors. Historical data on these inputs and actual sales are used to train the regression model, then expected future inputs generate sales forecasts.
The effectiveness of linear regression for forecasting depends on how well the model generalises to unseen data—which is evaluated using cross-validation.
Cross-Validation for Evaluating Forecasting Models
Cross-validation assesses predictive performance by splitting data into multiple subsets. A typical approach:
- Partition the data into a training set and a testing set.
- Train the regression model on the training set (it never sees the testing set).
- Evaluate performance on the testing set (unseen data) to measure generalisation.
During training, the model learns relationships by minimising the least‑squared error; variable selection can be guided by (R^2). Performance on the testing set checks for overfitting—good training performance but poor testing indicates the model has captured noise rather than genuine patterns.
K‑Fold Cross-Validation
Instead of one fixed split, the data is divided into (k) equal subsets (folds). The model is trained (k) times, each time using (k-1) folds as training and the remaining fold as testing. Accuracy is averaged across all (k) iterations, yielding a more robust estimate—especially useful when data is limited.
flowchart TD
A[Full dataset] --> B[Split into k folds]
B --> C[For i = 1 to k]
C --> D[Use fold i as test, rest as train]
D --> E[Train model]
E --> F[Evaluate on test fold i]
F --> G[Combine all k evaluations]
G --> H[Average performance metric]
Exam tip: K‑fold cross-validation ensures every observation is used for both training and testing, reducing the variance of the performance estimate. It is critical when selecting the best set of independent variables for forecasting.
Evaluating Predictive Accuracy for Continuous Data
Several metrics measure the difference between predicted ((\hat{y}_i)) and actual ((y_i)) values. Each provides different insight.
Common Metrics
| Metric | Formula | Unit | Interpretation |
|---|---|---|---|
| R‑squared ((R^2)) | Proportion of variance explained by model | Unitless (0–1) | Higher → more variance captured, but may overfit |
| Mean Absolute Error (MAE) | (\displaystyle \frac{1}{n}\sum_{i=1}^{n} | y_i - \hat{y}_i | ) |
| Mean Squared Error (MSE) | (\displaystyle \frac{1}{n}\sum_{i=1}^{n} (y_i - \hat{y}_i)^2) | Squared units of dependent variable | Penalises large errors more heavily |
| Root Mean Squared Error (RMSE) | (\displaystyle \sqrt{\frac{1}{n}\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}) | Same as dependent variable | Interpretable scale; sensitive to large errors |
| Mean Absolute Percentage Error (MAPE) | (\displaystyle \frac{100%}{n}\sum_{i=1}^{n} \frac{ | y_i - \hat{y}_i | }{y_i}) |
Detailed Notes on Each Metric
-
(R^2) (Coefficient of Determination): Represents the proportion of variance in the dependent variable explained by the model. Values range 0 to 1; 1 indicates perfect fit. High (R^2) can be misleading due to overfitting—it does not indicate absolute predictive accuracy and should be complemented by other metrics.
-
MAE: Average absolute error. For the house‑price dataset (price in lakhs of ₹), MAE is also in lakhs of ₹, giving a direct, intuitive measure of typical prediction error.
-
MSE: Squared error penalises outliers more than MAE. Because it is in squared units, it is harder to interpret directly. Useful when large errors are considered particularly harmful.
-
RMSE: The square root of MSE brings the unit back to the original scale (e.g., lakhs of ₹). It is the most interpretable error metric that still penalises large deviations.
-
MAPE: Expresses error as a percentage of actual value. For example, a 10% MAPE means predictions deviate on average by 10%. Especially valuable in finance and retail where relative accuracy drives decisions.
Exam tip: No single metric is sufficient. Use RMSE to detect large errors, MAE for average error, MAPE for relative error, and (R^2) for model comparison. Always evaluate on a held‑out test set via cross‑validation.
Key takeaways
- Linear regression forecasts continuous outcomes by fitting a linear equation; the model must generalise to unseen data.
- Cross‑validation (especially k‑fold) robustly evaluates generalisation by training/testing on multiple data splits.
- Predictive accuracy is measured with (R^2), MAE, MSE, RMSE, and MAPE—each highlights different aspects of error.
- Overfitting is detected when training performance is strong but test performance is weak.
- Errors on the house‑price example: MAE and RMSE in lakhs of ₹, MAPE as a percentage of the actual price.
The Problem Setup
We apply linear regression to a continuous target—house prices (in lakhs of rupees). The dataset contains 4,340 apartments. For validation, the first 3,000 observations form the training set and the remaining 1,340 form the test set. The goal: use apartment features to predict the price of an unseen house.
Features considered:
- RERA approval (binary)
- Number of bedrooms
- Area in sq. ft.
- Ready to move (binary)
- Resale (binary)
- Posted by (categorical: builder, owner, dealer)
Because posted by is categorical, it is encoded using a baseline category. Builder is set as the baseline; two binary dummy variables are created:
posted_by_owner(1 = owner, 0 otherwise)posted_by_dealer(1 = dealer, 0 otherwise)
The Regression Model
A linear regression is fitted on the training data:
\text{Price} = \beta_0 + \beta_1(\text{RERA}) + \beta_2(\text{bedrooms}) + \beta_3(\text{area}) + \beta_4(\text{ready_to_move}) + \beta_5(\text{resale}) + \beta_6(\text{posted\_owner}) + \beta_7(\text{posted\_dealer}) + \varepsilonEstimated coefficients from the output:
| Feature | Coefficient | Interpretation |
|---|---|---|
| Intercept | 571 | Baseline average price (lakhs) when all features = 0 |
| RERA approval | 21 | Add if approved (not statistically significant) |
| Number of bedrooms | 87 | Increase per extra bedroom |
| Area (sq. ft.) | — | Positive and significant (value not given, but used) |
| Ready to move | — | Significant (coefficient not stated) |
| Resale | — | Significant |
| Posted by owner | — | Significant (relative to builder) |
| Posted by dealer | — | Significant |
Exam tip: The intercept (571) is the predicted price when all continuous variables are zero and all dummies are zero (builder baseline, no RERA, not ready, not resale). This is often not practically meaningful but mathematically necessary.
Making Predictions
For a new apartment, the predicted price is the sum of the intercept plus each applicable coefficient. Example procedure:
- Start with 571 (intercept)
- Add 21 if RERA-approved
- Add 87 × number of bedrooms
- Add coefficient × area (sq. ft.)
- Add coefficient if ready-to-move
- Add coefficient if resale
- Add coefficient if posted by owner or dealer
flowchart LR
A[Intercept 571] --> B{Add feature terms}
B --> C[+21 if RERA]
B --> D[+87 × bedrooms]
B --> E[+coef × area]
B --> F[+coef if ready]
B --> G[+coef if resale]
B --> H[+coef if owner or dealer]
C & D & E & F & G & H --> I[Predicted price]
Evaluating Forecast Accuracy
For each test observation, compute the error = actual − predicted. Four aggregated metrics:
Initial results on test set:
- MAE > 100 lakhs
- RMSE high
- MAPE > 130%
These seem poor. However, a closer look reveals the problem.
The Outlier Problem
A plot of actual vs. predicted values shows the model’s predictions max out around 1,600 lakhs, while some actual prices reach 9,000 lakhs. These extreme values (likely data entry errors or genuine outliers) inflate the error metrics.
After removing the 3–4 most extreme outliers (actual > 9,000), the actual and predicted price ranges become comparable. A scatter of actual vs. predicted clusters around the line, indicating reasonable performance for most observations.
Exam tip: Outliers can completely distort MAE, RMSE, and especially MAPE (since percentage error is sensitive to small denominators). Always examine the distribution before trusting global error metrics.
Improving the Model
Logarithmic transformation on the target variable can reduce skew and mitigate outlier impact:
After transformation, re-check for outliers and remove them only after careful analysis. This often yields a more normal-like distribution and better predictive performance.
Key takeaways
- Linear regression is a valuable tool for forecasting continuous data, but its effectiveness must be validated with a train/test split.
- Categorical features with >2 levels require dummy encoding with one baseline category.
- Outliers disproportionately affect regression coefficients and error metrics; visualization (actual vs. predicted) is essential.
- Removing outliers or applying log transformations can greatly improve model reliability.
- Even with good overall fit, some predictions may still be biased—further feature engineering or alternative models may be needed.
Predictive Analysis of Categorical Data
Logistic regression is a method for modeling binary outcomes – events that take only two values (yes/no, success/failure, purchase/no purchase). Unlike linear regression (which works for continuous response), logistic regression outputs a probability that an event occurs, bounded between 0 and 1. It does this by passing a linear combination of predictors through the logistic function:
Why it matters: businesses can use the predicted probability to classify customers as “likely to purchase” or not, then target marketing efforts accordingly.
Confusion Matrix
The confusion matrix is a 2×2 table that compares predicted classes (based on a probability threshold, typically 0.5) against actual classes.
| Predicted Positive (1) | Predicted Negative (0) | |
|---|---|---|
| Actual Positive (1) | True Positive (TP) | False Negative (FN) |
| Actual Negative (0) | False Positive (FP) | True Negative (TN) |
- TP: correctly predicted positive cases.
- TN: correctly predicted negative cases.
- FP: predicted positive but actually negative (Type I error).
- FN: predicted negative but actually positive (Type II error).
Key Metrics Derived from the Confusion Matrix
Accuracy
The fraction of all correct predictions:
Exam tip: Accuracy can be misleading when classes are imbalanced (e.g., 95% negative, 5% positive). A model that always predicts “negative” would achieve 95% accuracy but is useless for identifying positives.
Precision (Positive Predictive Value)
Out of all cases predicted as positive, how many were actually positive?
A high precision means few false positives.
Recall (Sensitivity, True Positive Rate)
Out of all actual positive cases, how many were correctly predicted?
A high recall means few false negatives.
F1 Score
The harmonic mean of precision and recall, balancing both:
- Always between 0 and 1; >0.5 is better than random.
- High only when both precision and recall are high.
Metrics trade-off: increasing precision often reduces recall and vice versa. The choice depends on business cost – e.g., in medical screening, missing a disease (low recall) may be worse than a false alarm (low precision).
AUC‑ROC Curve
The ROC curve plots Recall (TPR) against False Positive Rate (FPR) for all possible classification thresholds (from 0% to 100%).
- Threshold: the cutoff probability above which we predict “positive” (e.g., 0.5, 0.7). Changing threshold shifts TP/FP counts.
- Area Under the Curve (AUC) summarizes overall performance: AUC = 1 means perfect discrimination; AUC = 0.5 means random. AUC closer to 1 indicates better ability to separate the two classes.
- Particularly useful when the cost of misclassification varies (e.g., credit scoring, churn prediction).
Probabilistic Accuracy: Quadratic Score
Metrics above only evaluate classification correctness (which side of a threshold the predicted probability falls), not how well the probability itself matches reality.
Quadratic score (also called Brier score) measures the accuracy of the predicted probabilities:
- = actual outcome (1 or 0)
- = predicted probability of class 1
Lower values mean better probabilistic predictions (like MSE for continuous data). A model predicting 93% for a positive case is penalised less than one predicting 52%, even if both classify correctly.
Key Takeaways
- Logistic regression models binary outcomes via the logistic function, producing probabilities between 0 and 1.
- The confusion matrix is the foundation for computing accuracy, precision, recall, and F1 score.
- Precision answers “how reliable are positive predictions?”; recall answers “how many positives are caught?”; F1 balances both.
- AUC‑ROC evaluates discrimination ability across all thresholds – high AUC → good class separation.
- Quadratic score evaluates the accuracy of the probability estimates themselves, not just the binary classification.
- Selecting the right evaluation metric depends on business goals and the costs of false positives vs. false negatives.
Logistic Regression for Binary Classification (EdTech Company Case)
Logistic regression extends the linear model to predict a binary outcome — e.g., whether a customer converts (1) or not (0). Instead of modeling the outcome directly, it models the log-odds (logit) of the probability of conversion:
The probability is recovered via the inverse logit (sigmoid) function:
This keeps predictions in the (0,1) range, making them interpretable as probabilities.
Data and Variables
The EdTech company collected data on 9,240 potential customers. The target is Converted (1 = took a course, 0 = did not). The predictors used in the model:
| Variable | Type | Description |
|---|---|---|
| Open to Email | Binary (0/1) | Agreed to receive emails |
| Open to Call | Binary (0/1) | Agreed to receive calls |
| Total Visits | Continuous | Number of visits to the website |
| Total Time Spent | Continuous | Minutes spent on the site |
| Page Views per Visit | Continuous | Average pages viewed per visit |
| Indian | Binary (0/1) | Customer from India |
| Unemployed | Binary (0/1) | Currently unemployed |
| Student | Binary (0/1) | Currently a student |
| Better Career Prospects | Binary (0/1) | Selected “better career” as primary reason |
Training set: first 9,000 observations; test set: remaining ~240 observations.
Estimated Coefficients
The logistic regression coefficients (log-odds effects) are:
| Predictor | Coefficient | Interpretation (on log-odds) |
|---|---|---|
| Intercept | 0.954 | Baseline log-odds when all predictors = 0 |
| Open to Email | 1.178 | Positive: increased chance of conversion |
| Open to Call | –3.981 | Negative: decreased chance of conversion |
| Total Visits | 0.025 | Small positive effect per additional visit |
| Total Time Spent | (not given) | Positive (direction stated) |
| Page Views per Visit | –0.060 | Negative: more views → lower conversion (possible distraction) |
| Indian | (large negative) | Negative coefficient |
| Unemployed | (negative) | Negative (unexpected; possibly inability to pay) |
| Student | ~0 (near zero) | Negligible effect |
| Better Career Prospects | (large positive) | Strong positive effect |
Exam tip: A negative coefficient does not always mean the variable is “bad” — it means the log-odds of conversion decrease. Domain knowledge is needed to explain counterintuitive signs (e.g., unemployed → negative may reflect price sensitivity).
Worked Example: Predicting Probability for a New Customer
Given a customer with the following data:
- Open to Email = 1
- Open to Call = 1
- Total Visits = 2
- Total Time Spent = 60 minutes
- Page Views per Visit = ? (coefficient –0.060 used)
- Indian = 1
- Unemployed = 1
- Student = 0
- Better Career Prospects = 1
The logit is computed by summing the intercept and each coefficient multiplied by the variable value. Using the coefficients provided (and noting that the time‑spent coefficient was used but its value not disclosed), the cumulative logit is –1.458.
Convert to probability:
The model predicts only a 19% chance of conversion for this customer.
Model Evaluation on the Test Set
The predicted probabilities are thresholded at 50% to classify. The resulting confusion matrix:
| Predicted Converted (1) | Predicted Not Converted (0) | |
|---|---|---|
| Actual Converted (1) | TP = 51 | FN = 45 |
| Actual Not Converted (0) | FP = ? | TN = 118 |
Key metrics (as computed from the test set):
| Metric | Formula | Value |
|---|---|---|
| Accuracy | 69.29% | |
| Precision | 0.638 | |
| Recall (Sensitivity) | 0.531 | |
| F1 Score | 0.580 | |
| Quadratic (Brier) Score | 0.213 |
The model has decent precision but low recall — it misses many actual converters. The Brier score (0.213, where 0 is perfect and 1 is worst) suggests predictions are reasonably confident when correct.
Feature Engineering
- Create new features: e.g., interaction terms (Indian × Unemployed × Student), lead origin / source dummies.
- Transform skewed continuous variables: apply or to variables like Total Time Spent (likely right‑skewed).
- Domain‑specific features: incorporate business knowledge (e.g., previous engagement, discount eligibility).
Robust Cross-Validation
- The current split uses one‑fold (9,000 train / 240 test). Switch to 10‑fold cross‑validation to get more reliable performance estimates and reduce variance due to a single split.
Exam tip: When improving a logistic regression model, always start with feature engineering and transformation before tuning thresholds or trying more complex models. Cross‑validation helps confirm improvements are not coincidental.
Key takeaways
- Logistic regression models log-odds of a binary outcome; coefficients are additive on the log‑odds scale.
- The sigmoid transformation converts log-odds to probabilities between 0 and 1.
- Model evaluation uses confusion‑matrix derived metrics: accuracy, precision, recall, F1, and the Brier (quadratic) score.
- Counterintuitive coefficient signs (e.g., negative for unemployed) can arise — investigate with domain knowledge.
- Improvement strategies: feature engineering (interactions, transformations) and robust cross‑validation (e.g., 10‑fold).
Time Series Data
Time series data is data collected at successive points in time (daily, monthly, yearly) where the chronological order carries essential information. Unlike cross‑sectional data, the sequence itself is critical for understanding how values evolve.
Why specialized methods?
Conventional regression (e.g., OLS) treats observations as independent and ignores order, so it cannot detect patterns linked to time:
- Trend – a steady increase or decrease over time.
- Seasonality – regular cycles (e.g., higher sales in holiday seasons).
Time‑series methods capture these patterns, yielding better forecasts and informed decisions (e.g., stocking inventory before a seasonal peak).
Worked example: mean vs. trend
Given 7 observations:
| Observation | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 (??) |
|---|---|---|---|---|---|---|---|---|
| Set A | 2.6 | 2.1 | 2.4 | 2.0 | 2.5 | 2.2 | 2.3 | ? |
| Set B | 1.5 | 1.8 | 2.1 | 2.4 | 2.7 | 3.0 | 3.3 | ? |
- Set A: No clear pattern → the mean (~2.3) is a reasonable prediction.
- Set B: Clear upward trend – mean also ≈2.3, but a value around 3.0–3.3 is far more plausible. Using the mean here would be a poor forecast.
Exam tip: Always plot your time series first. A mean forecast works only when no trend or seasonality exists.
Three real‑world cases (from Forecasting: Principles and Practice)
| Case | Problem | Flawed method | Lesson |
|---|---|---|---|
| Disposable tableware manufacturer | Need monthly forecasts for hundreds of items with trend & seasonality | Average of last 6 or 12 months; linear regression on recent data only; linear trend from last year to this year | Using only recent data misses long‑term patterns – models must capture trend & seasonality |
| Australian pharmaceutical benefit scheme | Underestimated expenditure by ~$1 billion/year | Ignored sudden jumps due to policy changes and cheaper competitor drugs | Exogenous regressors (external info) are essential; not all patterns are in the historical series alone |
| Car fleet company | Forecast vehicle resale values; specialists resisted statistical models | Relied solely on expert judgment | Combine data, exogenous variables, and expert judgment for robust forecasts |
Core patterns in time series
graph LR
A[Time Series] --> B[Trend]
A --> C[Seasonality]
A --> D[Irregular / Noise]
B --> E[Upward / Downward / Flat]
C --> F[Weekly, Monthly, Yearly cycles]
Key takeaways
- Time series data is ordered chronologically – the order matters.
- Special methods are needed because conventional regression ignores time‑dependent patterns (trend, seasonality).
- A simple average (mean) fails when a trend is present.
- Good forecasting captures trend, seasonality, recent patterns, and exogenous regressors.
- Expert judgment can complement, but not replace, statistical models.
The French Bakery Sales Dataset
The dataset contains 600 days of sales (quantity sold) from a French bakery, spanning 2 Jan 2021 to 30 Sep 2022. Columns:
- Date (daily)
- Quantity (discrete count of products sold – note: the lecture distinguishes discrete quantity from continuous sales revenue)
- Day of week (for seasonality analysis)
Time‑series cross‑validation requires temporal order. When evaluating forecasting models, use the earlier part as the training set and the most recent part as the test set (never random splits). Here: train on all data up to 31 Aug 2022, test on September 2022 (last month).
Core Concepts: Trend and Seasonality
| Component | What it is | Real‑world example | Why it matters |
|---|---|---|---|
| Trend | Long‑term overall direction (upward, downward, flat, or piecewise changing) | A growing company’s annual revenue → upward trend; a product becoming obsolete → eventual decline | Strategic decisions: forecast growth, identify decline periods |
| Seasonality | Regular, predictable pattern repeating at fixed intervals (days, weeks, months, quarters) | Bakery sales peak on weekends, drop on weekdays | Anticipate short‑term fluctuations; prepare resources |
Trend can also be sinusoidal (e.g., winter wear – rises Sep–Jan, falls after, repeats yearly). Both components together let businesses separate a temporary seasonal dip from a long‑term declining trend.
Detecting Trend
1. Visual Inspection
Plot the time series as a line chart. For the bakery data:
- Early 2021: slight increase → then decline → again increase in 2022.
- Values fluctuate regularly (hint of weekly seasonality).
2. Moving Average
Smooths short‑term fluctuations to reveal the underlying trend.
- Period = window size. In Excel: add trendline → moving average → set period.
- (weekly): reveals short‑term trend.
- (monthly): shows month‑to‑month direction.
3. Linear Trend Line
Fits a straight line through all data points – assumes constant increase/decrease. The bakery data shows a very slight upward linear trend from start to end. Displays equation on chart.
4. Piecewise Linear Trend (mentioned but not detailed)
Better for non‑constant trends: fit separate straight lines to different time segments. Will be used later when specifying trend functions.
Detecting Seasonality
Step 1 – Compute averages per seasonal period
For weekly seasonality: group data by day of week and compute average quantity sold.
| Day | Average Quantity |
|---|---|
| Monday to Friday | 700–850 |
| Saturday | >1000 |
| Sunday | >1000 |
Weekends clearly above weekdays – strong weekly seasonal pattern.
Step 2 – Calculate Seasonal Index
Example: a Monday with sales 900 → index (above average).
Step 3 – Deseasonalize the Data
Remove seasonality to isolate trend: After deseasonalization, only trend and residual noise remain, enabling clearer trend analysis and better forecasting.
Exam tip: When performing time‑series cross‑validation, always use a time‑ordered train‑test split (e.g., first 80% as train, last 20% as test). Random splitting would leak future information into the training set.
Key takeaways
- Trend captures long‑term direction; seasonality captures fixed‑interval cycles.
- Detect trend via visual inspection, moving average, or linear/piecewise trend lines.
- Detect seasonality by averaging values per period (e.g., day‑of‑week) and computing seasonal indices.
- Deseasonalization separates the two components for more accurate forecasting.
- These concepts underpin advanced models (autoregressive, etc.) discussed later in the module.
Simple Forecasting Methods
Time series forecasting starts with methods that are intuitive and easy to apply. These simple methods (naive, seasonal naive, average, weighted average, drift) are often the first step before moving to more sophisticated techniques. Each captures a different assumption about how the past relates to the future.
Naive Method
The naive method assumes the most recent observation is the best forecast for all future periods. Formally, for a time series :
Intuition: If nothing is changing rapidly, the last value is a reasonable guess. Works well when data is stable or unpredictable (e.g., daily stock prices with no trend).
Worked example – Retail store daily sales (units):
| Day | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| Sales | 100 | 120 | 115 | 110 | 130 | 120 | 125 |
Forecast for next Monday (and all future days): 125 units (Sunday’s value). Graphically, a horizontal line at the last observation.
Limitations:
- Fails when data has strong trends or seasonality.
- Sensitive to random fluctuations – one outlier can distort all forecasts.
Seasonal Naive Method
The seasonal naive method extends the naive idea by repeating the observation from the same period in the previous season. For a season length :
Intuition: If a pattern repeats every week (or month, hour, etc.), the future should look like the most recent complete season.
Worked example – Same store, now with two weeks of data:
| Week | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| Week 1 | 100 | 120 | 115 | 110 | 130 | 120 | 125 |
| Week 2 | 210 | 240 | 230 | 220 | 260 | 300 | 340 |
Forecast for Week 3: copy Week 2 values → Monday = 210, Tuesday = 240, …, Sunday = 340. Graphically, the second week’s pattern repeats indefinitely.
Limitations:
- Assumes seasonal pattern is constant (no trend, no change in shape).
- Ignores any overall upward or downward movement across seasons.
Exam tip: Use seasonal naive when you see clear repeating cycles (weekly, monthly) and no trend. For stock market daily data (no strong seasonality), naive often beats seasonal naive.
Average Method
The average method uses the mean of all past observations as the forecast:
Intuition: When data is stable with no trend or season, the historical average is a reasonable guess.
Worked example – Coffee consumption (cups/day) over one week:
| Day | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| Cups | 4 | 3 | 2 | 5 | 3 | 1 | 1 |
Forecast for next Monday:
Compare: naive would give 1 cup (Sunday’s value), seasonal naive would give 4 cups (last Monday’s value). The average balances extremes.
Weighted Average Method
The weighted average method generalises the average by assigning different weights to observations, typically giving more to recent ones:
Weights are chosen by the analyst (e.g., linear increasing, exponential decay).
Intuition: Recent data may be more relevant, especially if trends or patterns shift. Weighted average lets you emphasise the end of the series.
Worked example – Coffee data with weights 1 (Monday) to 7 (Sunday):
| Day | Weight | Sales | Weight × Sales |
|---|---|---|---|
| Mon | 1 | 4 | 4 |
| Tue | 2 | 3 | 6 |
| Wed | 3 | 2 | 6 |
| Thu | 4 | 5 | 20 |
| Fri | 5 | 3 | 15 |
| Sat | 6 | 1 | 6 |
| Sun | 7 | 1 | 7 |
Sum weights = 1+2+3+4+5+6+7 = 28. Sum weighted sales = 4+6+6+20+15+6+7 = 64.
Because recent days (Sat, Sun) had low values, the forecast is lower than the simple average (2.71). Weighted average is useful when recent trends dominate (e.g., sales during a promotion).
Drift Method
The drift method assumes a constant average change between consecutive observations. The forecast is the last observation plus the average per‑period change:
Intuition: When data shows a clear upward or downward trend (sales growth, population increase), drift captures that directional movement.
Worked example – Product sales over 7 days:
| Day | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| Sales | 10 | 12 | 15 | 17 | 20 | 22 | 25 |
First observation , last , days of data → time steps.
Average change: units per day.
Forecast for next Monday (): units. Forecast for Tuesday: units.
The forecast line continues the slope observed from the entire history.
Limitations:
- Assumes linear trend extends forever – unrealistic for long horizons.
- Sensitive to the first and last observations; outliers can distort the slope.
Choosing Among Simple Methods
| Method | Best when… | Ignores |
|---|---|---|
| Naive | Data is stable or random, no trend/seasonality | Trends, seasonality |
| Seasonal naive | Strong, repeating seasonal pattern (e.g., weekly, monthly) | Long-term trends |
| Average | Data is stationary with no trend/season | Recent changes, trends |
| Weighted average | Recent observations are more important than older ones | Seasonality (unless weighted accordingly) |
| Drift | Clear upward or downward linear trend | Seasonality, irregular fluctuations |
flowchart TD
A[Start: inspect time series] --> B{Strong seasonality?}
B -- Yes --> C[Use seasonal naïve]
B -- No --> D{Clear trend?}
D -- Yes --> E[Use drift method]
D -- No --> F{Recent changes important?}
F -- Yes --> G[Use weighted average]
F -- No --> H{Data stable?}
H -- Yes --> I[Use average or naïve]
H -- No --> J[Try naïve as baseline]
Exam tip: Simple methods are often used as benchmarks. Any advanced model should outperform the naive or seasonal naive forecasts. Many exam questions ask you to compute forecasts by hand using these methods – practice with small datasets.
Key Takeaways
- Naive: forecast = last observed value. Works for flat, noisy series.
- Seasonal naive: forecast = value from same period in previous season. Works for repeating patterns.
- Average: forecast = historical mean. Works for stationary data.
- Weighted average: forecast = weighted mean with higher weights on recent data. Captures recent shifts.
- Drift: forecast = last value + linear trend from first to last point. Works for trending data.
- All five are intuitive, easy to implement, and provide a foundation for advanced methods like exponential smoothing.
Exponential Smoothing Method
Exponential smoothing is a forecasting technique that computes a weighted average of past observations, assigning exponentially decreasing weights so that more recent data influences the forecast more heavily. It smooths out random fluctuations to reveal the underlying trend while still incorporating all historical data.
Intuition
Instead of equal weights (simple average) or arbitrary weights (weighted average), exponential smoothing uses a single parameter – the smoothing factor – to control how quickly the forecast adapts to new information.
- close to 1 → forecast reacts strongly to the most recent observation (rapid adaptation).
- close to 0 → forecast is influenced almost equally by all past data (heavy smoothing).
The method gets its name because the weights applied to past observations decay at an exponential rate.
The Core Formula
Let be the actual observation at time , and be the forecast for time (made at ). The forecast for the next period is:
Where:
- – smoothing factor.
- The initial forecast is usually set to the first observation (equivalent to the naive method for the first step).
Why “Exponential”? — Expanding the Formula
Repeatedly substituting reveals the weight structure:
The weight on observation is:
Because , the weight decreases geometrically (exponentially) as increases — older data matters less and less.
Worked Example: Ice Cream Shop Daily Sales
| Day | Actual Sales | Forecast (made previous day) | Calculation for next forecast |
|---|---|---|---|
| Mon | 100 | – | Set (initial naive) |
| Tue | 120 | 100 | |
| Wed | 115 | 110 | |
| Thu | 130 | 112.5 | |
| Fri | (unknown) | 121.25 | |
| Sat | … | … | … |
| Sun | 125 | (computed) |
Result: Forecast for next Monday ≈ 127 units (with ).
The Damping Factor
In many software implementations (e.g., Excel), the parameter requested is the damping factor rather than itself.
Exam tip: Always check which parameter a tool asks for. If it asks for “damping factor”, enter . A damping factor of 0.8 means (very heavy smoothing).
Why Use Exponential Smoothing?
| Reason | Explanation |
|---|---|
| Adaptability | Higher makes the forecast respond quickly to changes (e.g., a hot day spikes sales). |
| Simplicity | Only requires and the last actual + forecast; can be calculated by hand or in a spreadsheet. |
| Smoothness | Weights down extreme fluctuations, giving a clear view of the underlying trend and seasonality. |
Implementation in Excel
- Open Data Analysis Toolpak → select Exponential Smoothing.
- Input range: column of actual sales.
- Damping factor: enter (e.g., 0.2 for ).
- Set output range → click OK.
The resulting smoothed series tracks the data while reducing noise. A higher damping factor (lower ) produces a smoother line.
Visualising the Forecast Process
flowchart TD
A[Start: F₁ = y₁] --> B[Read new actual yₜ]
B --> C[Compute Fₜ₊₁ = α·yₜ + (1−α)·Fₜ]
C --> D[Update Fₜ = Fₜ₊₁]
D --> B
Key takeaways
- Exponential smoothing is a weighted average with weights decaying exponentially ().
- Smoothing factor (0 ≤ α ≤ 1) controls responsiveness: high α → fast adaptation, low α → heavy smoothing.
- The damping factor = ; Excel uses damping factor, not α.
- Initial forecast is usually the first observation (naive).
- Three strengths: adaptability, simplicity, smoothness.
- The method produces forecasts that react quickly to recent changes while still using all past data.
Autocorrelation and Autoregressive Models
Autocorrelation (also called lagged correlation or serial correlation) measures how a time series is correlated with its own past values. Intuitively: does today’s number carry information about tomorrow’s? In most business data – stock prices, daily sales, temperature – the past does influence the future. Autocorrelation quantifies that influence.
Mathematical definition
For a time series , the autocorrelation at lag is the Pearson correlation between the series and itself shifted by time steps:
In practice, to compute :
- Create two series: and .
- Compute their correlation (e.g.,
CORREL()in Excel).
Worked example – toy sales data
Given daily sales: values from 100 to 130, ending at 125 on Sunday (7 days).
For lag 1, align:
| Original | Lagged 1 |
|---|---|
| … | … |
The correlation of these two series equals 0.196.
Interpretation: a 1‑unit increase in past day’s sales is associated with a 0.2‑unit increase in the next day’s sales (linear approximation).
Extending to higher lags
- Lag 2: correlate with .
- Lag : correlate with .
Typically, autocorrelation decreases as the lag increases (e.g., today’s stock price influences tomorrow most, the day after a little less, etc.).
Sign of autocorrelation – what it tells you
| Autocorrelation sign | Pattern | Business example |
|---|---|---|
| Positive | High values followed by high; low followed by low | Daily store sales (recurring customer behaviour); warm days follow warm days |
| Negative | High values followed by low; low followed by high | Alternating marketing expenditure (high spend → budget cut next period) |
Exam tip: Positive autocorrelation is far more common in business. Negative autocorrelation often indicates deliberate alternating policies.
Autoregressive (AR) Models
An autoregressive model exploits autocorrelation by modelling the current value as a function of its own past values. The name literally means “regressing on itself”.
AR of order 1 – AR(1)
- = current value
- = value at previous time point
- = coefficient (strength of influence)
- = intercept
- = random error
Creating the lagged predictor: shift the series by one time step. Then run ordinary linear regression with as response and as predictor.
Bakery sales example
Data: daily sales from 2 Jan 2021 to 30 Sep 2022.
For an AR(1) model:
- Dependent variable: sales on day
- Independent variable: sales on day (lagged series)
Regression output (Excel Data Analysis ToolPak):
| Coefficient | Estimate | -value |
|---|---|---|
| Intercept () | 242.9 | ≈ 0 |
| Lagged sales () | 0.739 | ≈ 0 |
- Adjusted : ~54% – past day’s sales explains 54% of today’s variation.
- Both coefficients are statistically significant ().
Interpretation:
- If previous day’s sales were zero, expected sales = 242.9 units.
- For every 1‑unit increase in past sales, today’s sales increase by 0.739 units.
Prediction: Fitted equation:
On 30 Sep 2022, sales = 795.95 units. Prediction for 1 Oct 2022:
AR of order 2 – AR(2)
Extends to include two previous lags. The appropriate order is chosen by examining autocorrelation at multiple lags or using cross‑validation.
Exam tip: For an AR model to work, significant autocorrelation must exist in the data. Check the autocorrelation plot before fitting.
Choosing among forecasting methods – a recap
The lecture contrasted AR models with earlier methods. In practice, evaluate several candidates on a held‑out test set (last few observations) using root mean squared error (RMSE).
| Method | Core idea |
|---|---|
| Naïve | Use last observed value for all future forecasts |
| Seasonal naïve | Use last observed value from same season (e.g., last Monday for next Monday) |
| Average method | Forecast = sample mean of all past values |
| Weighted average | Weighted mean of all past values, higher weight on recent |
| Exponential smoothing | Weights decay exponentially: for values periods back |
| Drift method | Linear trend from first to last observation, projected forward |
| Autoregressive (AR) | Linear regression on own past values |
Cross‑validation procedure for time series:
- Hold out the last observations as the test set (e.g., last month).
- Train each method on the remaining data.
- Compute RMSE on the test set.
- Select the method with the smallest RMSE.
Key takeaways
- Autocorrelation measures how a time series correlates with its own past; it is the foundation of autoregressive models.
- is computed by correlating the series with its -lagged version; typically decays with .
- Positive autocorrelation: high → high; negative: high → low (rarer in business).
- AR(1): ; estimated via linear regression on the lagged variable.
- AR models require significant autocorrelation; order selection can use autocorrelation analysis or cross‑validation.
- Always compare AR with simpler benchmarks (naïve, exponential smoothing, drift) using a hold‑out RMSE.
A Case Study: Forecasting Gold Price in India (1964–2023)
This case study applies forecasting techniques to annual gold price data (1964–2023, 60 years). The dataset includes inflation as a potential predictor. The goal: predict gold price for the next year and evaluate which method works best. A cross-validation approach holds out the last 5 years (2019–2023) as a test set; the first 55 years train the models.
Questions and Data Overview
Six key questions guide the analysis:
- Is there a trend in gold price?
- Is there seasonality in this yearly series?
- Can past inflation (lagged) serve as a predictor in a linear regression model?
- Which simple methods (Naive, Seasonal Naive, Average, Weighted Average, Drift) perform well?
- What is the autocorrelation structure? Would an autoregressive model be suitable?
- Using cross-validation, which of the candidate models forecasts best?
1. Trend and Seasonality
Intuition: Visualizing the time series reveals overall behavior and whether trend or repeating cycles exist.
- The gold price plot shows a slow linear increase until ~2003, a dip around 2000, then exponential growth, another dip around 2012, followed by renewed exponential rise. The trend is erratic – not consistently linear or exponential – making a simple linear trend unsuitable.
- Seasonality is absent. Because the data is annual (yearly), repeating patterns within a year cannot exist. Any method relying on seasonality (e.g., Seasonal Naive, seasonal AR) is inappropriate.
Exam tip: For annual data, seasonality is impossible unless the series is recorded at sub‑annual intervals. Always check the frequency first.
2. Linear Regression with Inflation as Predictor
Intuition: Inflation is commonly believed to drive gold prices. A regression model uses lagged inflation (inflation from the previous year) to predict gold price.
- Model:
- Fitted equation (training data 1964–2018):
- The coefficient on inflation is not statistically significant (high p‑value). Although the common belief links gold to inflation, over the 60‑year period inflation changed little while gold prices soared. Inflation alone is a weak predictor.
- Predictions for 2019–2023 are poor. For 2019, predicted ≈ 7,775 vs. actual ≈ 35,000. RMSE is extremely high (similar to the simple average method).
Takeaway: Simple linear regression on a single, non‑trending predictor fails when the target has a strong time‑dependent growth.
3. Simple Forecasting Methods
Five simple methods were considered:
- Naive method: Forecast next year = last observed value. (Good benchmark, always included.)
- Seasonal naive: Requires seasonality – not applicable.
- Average method: Forecast = mean of all training data (55 years). Unlikely to capture rising trend.
- Weighted average method: Gives more weight to recent observations. Here, weights proportional to 1,2,3,4,5 for the last 5 years (most recent gets weight 5). Subjective – other schemes possible.
- Drift method: Assumes constant linear change per period; not suitable because trend is not linear over the whole period.
Decision: Only Naive, Average, and Weighted Average are used. Seasonal naive and drift are dropped.
Forecasts on test set (2019–2023):
| Year | Actual Gold Price | Naive (31,438) | Average (7,223) | Weighted Avg |
|---|---|---|---|---|
| 2019 | ~35,000 | 31,438 | 7,223 | ~23,000 (est) |
| 2020 | ... | 31,438 | 7,223 | increasing |
| ... | ... | ... | ... | ... |
| 2023 | ... | 31,438 | 7,223 | ... |
RMSE results:
- Average: ~43,567 (very poor)
- Naive: 20,536
- Weighted average: 12,869
Weighted average captures some upward trend by heavily weighting recent data, outperforming naive. Average method fails completely.
4. Autoregressive Model of Order 1 (AR1)
Intuition: Gold price is highly correlated with its own past. Autocorrelation measures this: a high, slowly decaying autocorrelation suggests an autoregressive (AR) model will work.
Autocorrelation values (training data):
| Lag | Autocorrelation |
|---|---|
| 1 | 0.989 |
| 2 | 0.964 |
| 3 | 0.935 |
| 4 | 0.908 |
Values are very high and decrease with lag – the farther back, the less influence on the present. This pattern supports an AR model.
AR1 model fitted:
- Coefficient of lagged gold is highly significant. For every unit increase in last year’s price, this year’s price increases by ~1.047 units (plus intercept).
- Forecasting for 2019: Use gold price in 2018 (31,438). Prediction: . Actual: 35,000. Error ~1,824.
- Repeating for all 5 test years yields RMSE = 6,568 – far lower than any simple method.
Why it works: The AR1 model captures the persistence and growth inherent in the series without assuming a fixed trend shape.
5. Cross-Validation Results Summary
| Method | RMSE (test set) |
|---|---|
| Linear regression (inflation) | ~43,500 (approx) |
| Average method | 43,567 |
| Naive method | 20,536 |
| Weighted average (last 5, weights 1-5) | 12,869 |
| AR1 model | 6,568 |
The AR1 model yields more than 100% improvement in RMSE over the next best (weighted average). The lecture notes that further refinements could include:
- Combining regression with AR (ARIMAX).
- Higher‑order AR (AR2, AR3).
- Adding trend terms (linear, exponential) as additional predictors in an AR framework.
6. Beyond: Improving the Model
The case study hints at more advanced approaches. For gold price, one could add a linear trend (time index 1,2,3,…) and an exponential trend () as extra regressors alongside the lagged gold. Running a regression with these would likely improve predictions further.
Contrast with bakery sales data (from earlier module): That data had seasonality, so seasonal naive and seasonal AR would be appropriate. This case shows that method selection must always match the data’s characteristics.
Exam tip: Always start with a naive forecast as a baseline. Any serious model must beat its RMSE. Here, AR1 beat it by a factor of 3.
Key Takeaways
- Annual data cannot have seasonality – skip seasonal methods.
- Visual inspection reveals trend shape (here: erratic, partly exponential) and zero seasonality.
- Simple linear regression on a single predictor (inflation) fails when the predictor lacks a time trend of its own.
- Among simple methods, weighted average (giving more weight to recent data) captured growth and outperformed naive.
- Autocorrelation was very high (0.99 at lag 1), making an AR1 model the best performer (RMSE 6,568 vs. 12,869 for weighted average).
- Cross-validation (hold‑out last 5 years) provided an honest comparison – AR1 was clearly superior.
- Always refine models by testing additional predictors (trend terms, other economic variables) and higher AR orders.
Statistical Methods in Quality Management
Importance of Statistics in Quality Management
Quality management (QM) is a systematic approach to ensuring products, services, or processes meet or exceed customer expectations. It integrates planning, monitoring, and improvement of operations to deliver consistent, reliable outcomes. Core principles include customer focus, process optimization, continuous improvement, and evidence-based decision making. Frameworks such as Total Quality Management (TQM) , Six Sigma, and ISO standards provide structured methods to reduce errors, increase efficiency, foster customer satisfaction, and maintain competitive advantage.
Statistics supplies the tools to measure, analyze, and improve quality scientifically. By applying statistical methods, organizations can:
- Quantify variation in processes.
- Identify root causes of defects.
- Implement solutions for consistent performance.
Key Statistical Techniques in QM
| Technique | Purpose in Quality Management |
|---|---|
| Control charts (Statistical Process Control) | Monitor process performance over time; detect deviations before they escalate |
| Sampling | Assess product quality without inspecting every unit – saves time and cost |
| Estimation (sample means, standard deviations) | Infer population parameters from samples to check adherence to standards |
| Hypothesis testing | Determine whether a process meets required standards |
| Regression analysis | Identify factors (e.g., in manufacturing) that influence defects |
| Design of experiments (DOE) | Optimise formulations or processes (e.g., pharmaceutical drug development) |
Intuition: Why Statistics Matters
A manufacturing process (or any pipeline) produces a stream of items. Inspecting every item is impossible for time and cost reasons. Instead, sample statistics (e.g., sample mean, sample standard deviation) are used to infer whether the entire output meets gold standards. Statistical techniques like estimation and hypothesis testing become critical for drawing these conclusions.
Six Sigma exemplifies the role of statistics in reducing process variability to achieve near-perfect quality levels. By using hypothesis testing, regression, or DOE, businesses detect deviations from the gold standard and pinpoint which part of the pipeline causes the deviation. This enables data-driven decisions that keep errors within acceptable limits.
Worked Examples (from industry)
- Automobile manufacturer uses regression analysis to identify factors correlated with defects in car components. The regression model reveals which process variables are positively correlated with defects, allowing targeted corrective actions.
- Pharmaceutical company uses design of experiments (DOE) to optimise the formulation of a new drug, systematically varying ingredients to find the best combination.
Benefits of Statistical QM
- Facilitates continuous improvement by providing measurable insights into process performance.
- Enables setting benchmarks and tracking progress.
- Supports evidence-based adjustments to meet quality standards.
- Ensures regulatory compliance in manufacturing, healthcare, and service delivery.
- Minimises waste and enhances customer satisfaction.
flowchart LR
A[Process / Pipeline] --> B[Sampling]
B --> C[Sample statistics<br>mean, std dev]
C --> D{Statistical Analysis}
D --> |Control charts| E[Monitor variation]
D --> |Hypothesis tests| F[Compare to standards]
D --> |Regression / DOE| G[Identify root causes]
E --> H[Detect deviations]
F --> H
G --> H
H --> I[Take corrective action]
I --> A
Key takeaways
- Quality management relies on evidence-based decisions; statistics provides the scientific measurement and analysis framework.
- Control charts and sampling are foundational for monitoring and cost-efficient inspection.
- Estimation and hypothesis testing let managers infer process behaviour from samples.
- Regression analysis and DOE help identify causes of defects and optimise products.
- Statistical methods transform quality management from abstract principle into a measurable, improvable process.
Hypothesis Testing in Quality Management
Hypothesis testing enables managers to decide whether an observed deviation in a process or product is due to random chance or signals a real problem. In quality management, these decisions have direct operational, financial, and safety consequences.
Type I and Type II Errors
Every test risks one of two mistakes. The null hypothesis () typically represents the “status quo” — that the process is acceptable. Rejecting means concluding there is a problem; failing to reject means no action is taken.
| Decision →<br>Reality ↓ | Reject | Do not reject |
|---|---|---|
| true | Type I error (false positive)<br>Conclude a problem exists when it does not | Correct decision |
| false | Correct decision | Type II error (false negative)<br>Conclude no problem when one exists |
Why each error matters in quality
-
Type I error () – “False alarm.”
Example: A batch that meets standards is rejected, causing unnecessary rework, scrap, or inspection costs.
Control: Set a low significance level (commonly or 0.01). -
Type II error () – “Miss.”
Example: A defective batch passes inspection, leading to recalls, legal liability, or safety hazards (e.g., faulty brake pads, wrong drug concentration).
Control: Increase sample size or test power ().
Exam tip: In quality, Type I errors waste money; Type II errors can kill people. Which error matters more depends on the consequence — not on a fixed rule.
Consequences of errors in quality management
| Impact | Type I dominant | Type II dominant |
|---|---|---|
| Financial losses | Rejecting good batches → increased cost | Failing to detect defects → recalls, warranty claims |
| Reputation | – | Substandard products damage trust |
| Operational efficiency | Excessive inspections / rework | – |
| Safety risks | – | Aviation, healthcare, food: catastrophic failures |
Key takeaways – Type I & II errors
- Type I = false positive (reject true ); Type II = false negative (fail to reject false ).
- (significance level) controls Type I; controls Type II (power = ).
- In manufacturing, Type I often drives cost; in safety-critical settings, Type II is paramount.
- Balancing errors requires setting appropriate , increasing sample size, and choosing the correct test.
Worked Examples
Example 1: Steel rod diameter (two-tailed test)
Situation: A factory produces steel rods with a target mean diameter mm. A random sample of rods yields mm, mm. Is the process misaligned?
- Hypotheses: vs. (two-tailed — both under‑ and over‑fill are unacceptable).
- Test statistic (t-test, since unknown):
- Null distribution: with .
- p-value: For a two-tailed test, (3.6%).
- Decision: → reject .
Conclusion: The observed deviation is unlikely due to chance. The machinery needs recalibration.
Example 2: Brake pad compressive strength (one-tailed test)
Situation: Minimum acceptable mean compressive strength is 100 MPa. A sample of brake pads gives MPa, MPa. Does the supplier meet the standard?
- Hypotheses: vs. (one-tailed — only under‑strength is a concern).
- Test statistic:
- Null distribution: with .
- p-value: (5.6%).
- Decision: → do not reject .
Conclusion: There is insufficient evidence to claim the supplier is substandard. The sample mean of 99.3 MPa could be due to random variation. (Recommend increasing sample size for a definitive verdict.)
Exercises for practice
- Sugar packaging: A company fills 1‑kg bags. Suspecting underfilling, they sample bags: kg, kg. Formulate hypotheses and decide (one‑tailed? two‑tailed?) whether the filling machine needs adjustment.
- Call center wait times: Before a new scheduling system, average wait time was 4.5 min. After, a sample of calls shows min, min. Test whether the system effectively reduced wait time.
Key takeaways – Hypothesis testing in practice
- Choose the right tail: Two-tailed when any deviation is unacceptable; one-tailed when only a specific direction matters (e.g., under‑strength, over‑weight).
- Use ‑test when unknown — the most common case in quality.
- Context drives the decision: A “non‑significant” result (p > 0.05) may still warrant follow‑up with a larger sample if the consequence of a Type II error is severe.
- Hypothesis testing enables early detection, supplier accountability, evidence-based process changes, and cost savings from reduced waste/rework.
Regression Analysis to Model Input and Output Relationships in Quality Control
Regression analysis models how input variables (independent variables) affect an output variable (dependent variable). In quality control, this quantifies the relationship between process factors and product quality, enabling prediction, identification of key drivers, and optimization of operating conditions. By understanding which inputs matter and by how much, teams can reduce variability, minimize defects, and make data-driven improvements.
Importance of Regression in Quality Control
- Identify key drivers – Determines which factors (e.g., machine temperature, raw material properties) significantly influence quality or defect rates.
- Quantify relationships – Produces a mathematical model that predicts output from input values, supporting proactive decision-making and scenario forecasting.
- Find optimal settings – Helps minimize defects, risks, or costs by selecting input levels that keep the output within acceptable bounds.
- Understand sources of variability – Reduces unwanted variation by isolating which inputs contribute to inconsistency.
- Support Six Sigma initiatives – Provides evidence for reducing defects, rework, and costs through targeted process changes.
Linear Regression: Worked Examples
The general linear regression model with multiple inputs is written as:
where is the output, are inputs, are coefficients, and is random error.
Example 1: Controlling Product Weight in Packaging
A food company packages 1‑kg bags. Two inputs are suspected to affect bag weight: machine speed (bags per minute) and hopper pressure (psi). Data collected at various settings yields the following linear regression results:
- Every increase of 10 bags per minute → bag weight decreases by 0.02 kg.
- Every increase of 5 psi → bag weight increases by 0.01 kg.
The company uses scenario forecasting to predict weight at different input combinations, e.g., machine speed = 40 bags/min and hopper pressure = 15 psi gives a weight closest to 1 kg. Multiple acceptable settings may exist; the regression model provides the flexibility to choose a feasible, compliant combination.
Example 2: Defect Rate in an Assembly Line
An electronics manufacturer wants to predict the percentage of defective units based on two inputs: worker training hours and machine maintenance frequency (days since last maintenance). Regression results:
- Every additional 5 hours of training → defect rate decreases by 4 %.
- Every additional 5 days since last maintenance → defect rate increases by 6 %.
The company seeks an optimum level, not necessarily zero defects, because unlimited training or daily maintenance would incur prohibitive costs. For an acceptable threshold of 10 % defects, the model suggests, e.g., maintaining machines every 10 days and providing at least 15 hours of training. This balances quality with cost.
| Example | Input variables | Effect on output | Objective |
|---|---|---|---|
| Packaging weight | Machine speed, hopper pressure | Speed ↓ weight; pressure ↑ weight | Find settings that yield weight ≈ 1 kg |
| Assembly defects | Training hours, days since maintenance | Training ↓ defects; maintenance delay ↑ defects | Keep defects ≤ 10 % at minimal cost |
Logistic Regression in Quality Control
Logistic regression is used when the output variable is binary, e.g., pass/fail, in control/out of control. It models the probability of an event (e.g., defect) as a function of predictors:
Example: A manufacturer wants to predict the probability that a product fails quality checks based on temperature, pressure, and machine speed. Logistic regression quantifies how each predictor affects the odds of failure. The manager can:
- Identify which factors contribute most to quality issues (high positive coefficients).
- Estimate the likelihood of defects under current process conditions.
- Determine optimal ranges for predictors to minimize defect probability.
- Pinpoint high-risk factors for immediate corrective action.
Exam tip: Logistic regression is ideal for binary quality outcomes (e.g., defective vs. non‑defective, conforming vs. non‑conforming). It provides probabilities, not continuous predictions, and is sensitive to sample size and class balance.
Key takeaways
- Regression (linear or logistic) quantifies how inputs affect outputs in quality management.
- Linear regression predicts continuous outcomes (weight, defect percentage) and aids scenario forecasting.
- Logistic regression predicts binary outcomes (pass/fail) and estimates probabilities of defects.
- Both methods identify key drivers and support optimization, but practical constraints (cost, feasibility) often require a target acceptable level rather than absolute perfection.
- Regression is a cornerstone for data-driven process improvement, variability reduction, and Six Sigma.
Statistical Decision Theory – Introduction
Statistical decision theory provides a structured framework for making choices when outcomes depend on uncertain events. The core idea: combine probabilities, data, and decision rules to minimize risk or maximize expected payoff. Every business manager faces decisions under uncertainty — the quality of those decisions hinges on the quantity and quality of available information.
Elements of the Decision Process
Every decision problem under uncertainty contains four components:
- Alternative courses of action (acts/strategies) – the options the decision maker can choose (e.g., launch a new product vs. expand marketing).
- States of nature – uncertain, uncontrollable events that affect outcomes (e.g., high market demand vs. low market demand).
- Payoff – a numerical value (profit, cost, utility) conditional on the combination of an action and a state. The payoff is always conditional because the state is unknown at decision time.
- Decision rule – the criterion for selecting the best action, based on the decision maker’s goals and available information.
Payoff Matrix
A payoff matrix is a table that displays the payoff for every action–state pair. It enables direct comparison of outcomes under different scenarios.
Payoff matrix = each row an action, each column a state, each cell the payoff for that combination.
Example: Product Launch vs. Marketing Expansion
| Action | State: High demand | State: Low demand |
|---|---|---|
| Launch new product | ₹200,000 | ₹50,000 |
| Expand marketing for existing product | ₹150,000 | ₹100,000 |
The decision maker cannot simply pick the maximum payoff (₹200,000) because that payoff is contingent on "high demand" occurring. The matrix forces explicit consideration of both possibilities.
Opportunity Loss (Regret) Matrix
The opportunity loss matrix (or regret matrix) quantifies the cost of not choosing the best action for each state. It is constructed as:
Steps to build it:
- For each state, identify the maximum payoff across all actions.
- In each column, subtract every payoff from that column’s maximum.
Regret Matrix for the Example
- High demand: max payoff = ₹200,000 (Launch)
- Low demand: max payoff = ₹100,000 (Expand)
| Action | Regret in High demand | Regret in Low demand |
|---|---|---|
| Launch new product | ₹200k − ₹200k = ₹0 | ₹100k − ₹50k = ₹50,000 |
| Expand marketing | ₹200k − ₹150k = ₹50,000 | ₹100k − ₹100k = ₹0 |
Interpretation: If the firm launches the product and demand turns out to be low, it loses ₹50,000 compared to what it could have earned by expanding marketing.
flowchart LR
A[Decision problem] --> B[Payoff matrix: direct profit]
A --> C[Opportunity loss matrix: regret of non-optimal choice]
B --> D[Used when probabilities are known, risk-neutral]
C --> E[Used for minimax regret, conservative]
When to use each:
| Matrix | Use case |
|---|---|
| Payoff matrix | Maximise expected profit when state probabilities can be estimated |
| Opportunity loss matrix | Minimise maximum possible regret when probabilities are unknown or decision maker is cautious |
Exam tip: The regret matrix is not an alternative payoff matrix — it is derived from the payoff matrix. A common mistake is to confuse the two. Regret always uses the difference from the best-in-column.
Key takeaways
- Four elements: actions, states of nature, conditional payoffs, and a decision rule.
- A payoff matrix organises all possible outcomes for each action–state pair.
- An opportunity loss matrix shows the regret of not picking the best action in each state; each cell = column max − actual payoff.
- The same example can be analysed with either matrix depending on whether the goal is reward maximisation or regret minimisation.
Concept of Decision-Making Under Uncertainty
Decision theory (or decision analysis) formalizes the process of choosing among alternative courses of action when at least two alternatives exist. The decision environment is classified by the amount of information available about the outcomes:
- Certainty – The outcome of each action is known perfectly. The decision is trivial: pick the action with the largest payoff. Statistically uninteresting.
- Uncertainty – More than one possible outcome (state of nature) exists, but the decision-maker cannot assign probabilities to them.
- Risk – States of nature exist and the decision-maker can assign probabilities (objective or subjective) to each.
Decision Process
- Identify and define the problem.
- List all possible future events – the states of nature ().
- Identify all possible courses of action (alternatives) – .
- Construct a payoff table showing the payoff (profit, cost, etc.) for every combination of action and state of nature.
- Choose a decision criterion (rule) to select the best action.
Decision Making Under Uncertainty
The decision-maker has knowledge of the possible states of nature but lacks any information about their likelihoods. Four classic criteria are used:
1. Maximax Criterion (Criterion of Optimism)
Select the alternative that yields the maximum of the maximum payoffs.
- For each alternative, find the highest payoff across all states.
- Choose the alternative with the largest of these maxima.
Exam tip: Maximax is unrealistically optimistic; it assumes the best-case scenario will occur.
2. Maximin Criterion (Criterion of Pessimism)
Select the alternative that yields the maximum of the minimum payoffs.
- For each alternative, find the lowest payoff across all states.
- Choose the alternative with the largest of these minima.
This ensures a guaranteed worst-case floor – a conservative, security-oriented approach.
3. Minimax Regret Criterion (Opportunity Loss / Minimum Regret)
Minimises the maximum opportunity cost (regret) of a decision.
Procedure:
- For each state of nature, identify the best possible payoff.
- For each action–state combination, compute regret = best payoff in that state − actual payoff.
- For each alternative, find the maximum regret.
- Select the alternative with the minimum of those maximum regrets.
flowchart TD
A[Compute regret for each action-state] --> B[Find max regret per action]
B --> C[Select action with smallest max regret]
This criterion strikes a balance: it limits the worst regret a manager can experience, though it may sacrifice high rewards.
4. Hurwicz Criterion (Criterion of Realism)
A compromise between maximax and maximin. The decision-maker chooses a coefficient of optimism (), where gives maximax and gives maximin.
For each alternative , compute:
Select the alternative with the highest .
Worked Example: Biscuit Selection
A shopkeeper must choose one biscuit brand: Marigold, Good Day, or Oreo. Three possible states of nature: expected sales next year – Low, Medium, High. Payoffs in thousands of rupees:
| Alternative | Low (5,000 units) | Medium (10,000 units) | High (20,000 units) |
|---|---|---|---|
| Marigold | 15 | 30 | 45 |
| Good Day | 20 | 40 | 65 |
| Oreo | 25 | 50 | 70 |
Maximax:
Maximum payoffs: Marigold = 45, Good Day = 65, Oreo = 70 → choose Oreo.
Maximin:
Minimum payoffs: Marigold = 15, Good Day = 20, Oreo = 25 → choose Oreo.
Minimax Regret:
First compute the best payoff in each state:
- Low: 25 (Oreo)
- Medium: 50 (Oreo)
- High: 70 (Oreo)
Regret table (best − actual):
| Alternative | Low | Medium | High | Max Regret |
|---|---|---|---|---|
| Marigold | 10 | 20 | 25 | 25 |
| Good Day | 5 | 10 | 5 | 10 |
| Oreo | 0 | 0 | 0 | 0 |
Select Oreo (minimax regret = 0). In this example all three criteria select Oreo.
Hurwicz with :
- Marigold:
- Good Day:
- Oreo: → choose Oreo.
Since both extremes point to Oreo, any weighted average also points to Oreo. This is not always the case, as seen next.
Additional Example: Bottling Company (Take-Home Exercise)
A company must choose among three actions to meet rising demand: Expand existing plant, Construct a new plant, or Subcontract production. Four states of nature: High, Medium, Low, or None (demand). Payoffs in thousands of rupees:
| Action | High | Medium | Low | None |
|---|---|---|---|---|
| Expand | 50 | 20 | -25 | -45 |
| Construct | 70 | 30 | -40 | -80 |
| Subcontract | 30 | 15 | -5 | -10 |
Applying the criteria will yield different optimal actions:
- Maximax → Construct (70).
- Maximin → Subcontract (−10 is the highest minimum).
- Minimax regret → Compute regret and select the action with smallest max regret (likely Subcontract or Expand).
- Hurwicz → Varies with ; at :
- Expand:
- Construct:
- Subcontract: → Subcontract.
Exam tip: When maximax and maximin give different answers, Hurwicz offers a flexible middle ground. Always check how changing alters the decision.
Key Takeaways
- Under uncertainty, no probabilities are known; under risk, probabilities are assigned.
- Maximax – optimistic; Maximin – pessimistic; Minimax regret – minimises worst-case opportunity loss; Hurwicz – weighted average of best and worst.
- The choice of criterion heavily influences the decision; in some problems different criteria recommend different actions.
- The Hurwicz parameter reflects the manager’s degree of optimism.
Concept of Decision Trees
A decision tree is a graphical tool for evaluating multiple decision alternatives under uncertainty. It breaks down complex decisions into sequential steps, mimicking natural decision-making. Each node is a decision point or a chance event; branches represent possible choices or outcomes with associated probabilities and payoffs. The structured approach allows decision makers to visualize chains of events and systematically weigh risks and rewards.
Decision trees are widely used in business analytics, finance, marketing, operations, and quality management to optimise strategies and reduce uncertainty. The core objective: compute the expected monetary value (EMV) of each branch and choose the path with the highest expected payoff.
Example: Launching a New Smartwatch
A retail company must decide whether to launch a new smartwatch immediately or conduct market research first. Uncertainties include market reception (success or failure), research outcome (favours launch or not), and associated costs/probabilities. The decision tree captures all paths and their EMVs.
flowchart TD
A[Decision] --> B1[Launch immediately]
A --> B2[Conduct market research\n(cost: ₹200,000)]
B1 --> C1[Success (0.6)]
B1 --> C2[Failure (0.4)]
B2 --> D1[Research favours launch (0.7)]
B2 --> D2[Research does not favour launch (0.3)]
D1 --> E1[Success (0.6)]
D1 --> E2[Failure (0.4)]
D2 --> F1[Abandon: loss = research cost]
C1 -->|Profit ₹1,000,000| G1[EMV₁]
C2 -->|Loss ₹500,000| G1
E1 -->|Profit ₹1,000,000| G2[EMV₂ sub-branch]
E2 -->|Loss ₹500,000| G2
F1 -->|Loss ₹200,000| G2
EMV calculation
-
Launch immediately:
-
Market research first:
- If research favours launch (70 % chance), the sub‑branch EMV is the same as above: ₹400,000.
- If research does not favour launch (30 % chance), the loss is only the research cost: ₹200,000.
- Overall EMV:
Since ₹400,000 > ₹80,000, the optimal decision is launch immediately.
Exam tip: Always subtract the research cost from the total EMV of the research branch — a common oversight. The EMV of the launch branch already accounts for the profit/loss numbers given.
Decision Trees for Quality Control Decisions
Decision trees also apply to batch inspection in manufacturing. A manager must decide: approve, perform further tests, or reject a batch based on sample defect rates. The tree uses pre‑defined thresholds derived from historical data.
Example: Automobile Parts Batch Inspection
- Each batch contains 1,000 parts; a random sample of 50 is inspected.
- Decision thresholds (from historical analysis):
- Defect rate < 2 % → approve batch.
- Defect rate 2–5 % → borderline; conduct further testing.
- Defect rate > 5 % → reject batch.
For a sample of 50 parts:
- 0 or 1 defective → approve (defect rate ≤ 2 %).
- 2, 3, or 4 defective → further testing.
- 5 or more defects → reject (defect rate ≥ 10 %).
flowchart LR
A[Sample (n=50)] --> B{Defect count}
B -->|0–1 defects| C[Approve]
B -->|2–4 defects| D[Further testing]
B -->|≥5 defects| E[Reject]
Setting Thresholds with Historical Data
Rather than arbitrary cutoffs, thresholds should be data‑driven. Two common approaches:
-
Percentile analysis – Examine the distribution of defect rates from past batches. Identify natural cutoffs where higher defect rates are associated with high rework costs or customer returns. For example, the 90th percentile might mark the point beyond which rejection is economically justified.
-
Cost‑benefit simulation – Define the costs of each decision:
- Scrap cost (rejecting a good batch)
- Inspection cost (further testing)
- Failure cost (defective products reaching customers – returns, warranty claims, legal risks)
Simulate different threshold pairs (e.g., lower=1 %, upper=3 %; lower=2 %, upper=5 %) and compute total expected cost. The optimal thresholds minimise total cost.
Exam tip: Threshold selection is a trade‑off between strictness (high rejection → scrap cost) and leniency (high defect rate shipped → failure cost). Always consider both sides in an exam problem.
Automation and Continuous Improvement
- Once thresholds are set, the decision tree can be automated – every new batch is sampled, classified, and routed to the appropriate action without manual intervention.
- Continuous improvement: Re‑evaluate thresholds periodically (monthly/quarterly) using updated defect patterns to adapt to process changes.
Key takeaways
- A decision tree maps decisions, chance events, probabilities, and payoffs into a clear visual framework.
- EMV is the core metric: – choose the branch with the highest EMV.
- In quality control, decision trees classify batches based on sample defect rates and predefined thresholds (e.g., approve if ≤2 defects/n).
- Thresholds should be derived from historical data using percentiles or cost‑benefit simulations, not guesswork.
- Decision trees enable automated quality assurance, reducing subjective judgment and improving product quality.
Statistical Process Control (SPC)
Statistical Process Control (SPC) is a data-driven methodology used to monitor and control processes so that they produce consistent, reliable output. The core insight: every process has inherent variation. SPC helps distinguish normal variation from abnormal variation — enabling early corrective action before defects occur.
Types of Process Variation
- Common cause variation – natural, expected fluctuations from minor, uncontrollable factors. Low magnitude, always present.
- Special cause variation – unusual, large disturbances from specific issues (equipment failure, human error, environmental change). Indicates a process out of control.
flowchart LR
A[Process variation] --> B[Common cause: natural, low magnitude]
A --> C[Special cause: assignable, high magnitude]
B --> D[Process stable (in control)]
C --> E[Process unstable (out of control) – investigate]
SPC provides tools to differentiate these two types and maintain process stability.
Key SPC Tools
Control charts are the most essential; also used: histograms, Pareto charts, process capability analysis. This section focuses on control charts (also called Shewhart charts, after Walter A. Shewhart, 1920s).
Control Charts: Structure & Purpose
A control chart is a graphical tool that tracks a process metric over time. Every control chart has three components:
| Component | Description |
|---|---|
| Central line (CL) | The average or expected value of the process |
| Upper control limit (UCL) | Upper bound of acceptable variation |
| Lower control limit (LCL) | Lower bound of acceptable variation |
| Data points | Actual observations plotted over time |
A process is stable (in control) when all points fall within the control limits and show no unusual patterns. Any point outside the limits, or a systematic trend, signals a special cause that requires investigation.
Worked Example: Email Response Time
A company monitors daily average response time (minutes) for 15 days.
| Day | 1 | 2 | 3 | 4 | 5 | … | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|
| Time | 12 | 15 | 14 | ? | ? | … | ? | ? | >22 |
- Mean response time = 16 minutes → central line at 16.
- Initially, UCL = 22, LCL = 10 (chosen subjectively as ±6 minutes).
Points on day 13 touch the limit; day 15 exceeds the UCL. Also an increasing trend from day 1 to day 15. This suggests a special cause (e.g., increased queries, system downtime, staffing issues) → investigate and correct.
Setting Control Limits: The Empirical Rule
Subjective limits are not ideal. A rigorous, data-driven approach uses confidence intervals based on the normal distribution. The standard rule:
where is the process mean and the process standard deviation.
Why ±3σ? The Empirical Rule
For normally distributed data:
- of observations lie within
- within
- within
Thus, only 0.3% of points fall outside ±3σ under common-cause variation. A point beyond ±3σ is strong evidence of a special cause.
Re‑evaluating the Example
The response‑time data had , . Using ±3σ:
All 15 observations now fall within these wider limits. The process appears in control under the ±3σ rule (no points outside). This demonstrates how changing the limit rule changes the diagnosis.
Exam tip: The ±3σ rule is the most common control‑limit choice. Always check whether limits are given as subjective values or computed from the data.
Six Sigma: A Stricter Standard
Six Sigma is a methodology for reducing defects and variability. In SPC, it extends the control‑limit concept to ±6σ from the mean.
For a perfectly normal process:
- of points lie within
- Only fall outside → 3.4 defects per million opportunities
This extremely low defect rate is the Six Sigma target. If a point falls outside ±6σ, it almost certainly indicates a special cause.
| Rule | % within limits | Defects per million (approx.) |
|---|---|---|
| ±3σ | 99.73% | 2700 |
| ±6σ | 99.99966% | 3.4 |
Six Sigma is widely adopted in manufacturing, healthcare, and finance to maintain high quality through continuous monitoring and improvement.
Key Takeaways
- SPC distinguishes common cause (normal) from special cause (assignable) variation.
- Control charts (Shewhart charts) plot process data over time with a central line and two control limits (UCL, LCL).
- The standard data‑driven limit is , based on the empirical rule (99.7% coverage).
- Points outside ±3σ signal a special cause → investigate.
- Six Sigma uses limits, aiming for only 3.4 defects per million.
- Control charts enable early detection of process shifts, trends, and outliers, supporting proactive quality management.
Statistical Process Control – Control Charts
Statistical process control (SPC) is a methodology for monitoring, controlling, and improving production processes. The most widely used SPC tool is the control chart – a visual, time‑ordered display of process variation that flags when a process is drifting outside acceptable limits and corrective action is needed.
Four common types are covered: X‑bar chart, R chart, P chart, and NP chart. Each is designed for a specific data type and monitoring purpose.
X‑bar and R Charts (Mean and Range Charts)
Intuition: When the process output is a continuous measurement (weight, length, temperature), we care about both the average level and the spread. The X‑bar chart tracks the mean; the R chart tracks the range (max – min) within each sample. Together they detect shifts in location (e.g., machine calibration drift) and changes in variability (e.g., tool wear).
Use case: Continuous variables – e.g., weight of tablets, length of metal rods, fuel efficiency, time to complete a job.
Two charts in one:
- X‑bar chart – monitors the process mean over time. Centre line = overall mean . Upper and lower control limits (UCL, LCL) are typically set at (or using factor times average range).
- R chart – monitors process variability. Centre line = average range . Limits use factors and (or equivalent).
Worked Example – Pharmaceutical Tablet Weight
A company produces tablets of target weight 500 mg. Every hour a sample of 5 tablets is weighed for 10 hours.
| Sample | Tablet 1 | Tablet 2 | Tablet 3 | Tablet 4 | Tablet 5 | Sample Mean | Range |
|---|---|---|---|---|---|---|---|
| 1–10 | … | … | … | … | … | … | … |
Computed overall mean: mg
Average range: mg
Standard deviation of sample means: mg
Using ±3σ limits (stated as “6‑sigma limits”):
- UCL = mg
- LCL = mg
All sample means fall inside these limits → process mean is stable.
Similarly, the R chart with centre line 0.91 mg shows all ranges within control limits → variability is stable.
Interpretation: If an X‑bar point exceeds UCL/LCL → possible calibration issue or ingredient mixing error. If an R point rises → increasing variability (e.g., dull cutting tool, inconsistent mixing).
Key takeaways – X‑bar and R charts
- Used for continuous data; monitor both mean (X‑bar) and spread (R).
- Centre line for X‑bar = ; for R = .
- Points outside control limits signal need for investigation.
- Common in manufacturing, pharma, food processing.
P Chart (Proportion Chart)
Intuition: When quality is measured as pass/fail (attribute data), we monitor the proportion of defective items. The P chart tracks this proportion over time, with control limits that adjust for changing sample sizes.
Use case: Categorical data – pass/fail, complaint/not complaint, defective/acceptable.
- Centre line = overall proportion .
- Upper control limit and lower control limit vary with sample size because the standard error of a proportion depends on :
- UCL and LCL are typically .
Example – Call Centre Complaints
A call centre records daily customer complaints. Data includes:
| Day | Calls | Complaints | Proportion |
|---|---|---|---|
| 1 | 100 | 5 | 0.05 |
| … | … | … | … |
| 5 | 120 | 15 | 0.125 |
| 6 | 90 | 1 | 0.011 |
| … | … | … | … |
| 10 | 110 | 14 | 0.127 |
Because sample size (number of calls) changes each day, the control limits are not constant – they widen when is small and narrow when is large.
A point above the UCL (e.g., day 5 or 10) signals an unusually high complaint rate that warrants investigation – possible staffing shortage, training gap, or software issue. A point below the LCL (e.g., day 6) might indicate a truly good day or underreporting; both should be examined.
Exam tip: P‑chart limits are variable when sample sizes differ. Do not compare a point to a fixed limit – always check the local UCL/LCL for that sample.
Key takeaways – P chart
- Used for attribute data (pass/fail, defective/non‑defective).
- Monitors proportion of defects; limits vary if sample size varies.
- Points outside limits indicate special‑cause variation.
- Investigate both high and low outliers (low may be underreporting).
NP Chart (Number of Defectives Chart)
Intuition: When sample size is constant, it is simpler to plot the count of defective items rather than the proportion. The NP chart does exactly that – it tracks the raw number of defects.
Use case: Constant sample size across subgroups.
- Centre line = average number of defectives .
- Control limits: .
Example: A bakery produces 500 loaves daily and inspects each batch for defects (undercooked, burnt crust). The number of defective loaves is plotted each day. An increasing trend might indicate temperature control problems.
Key takeaways – NP chart
- Similar to P chart but tracks count of defectives.
- Requires constant sample size.
- Simpler to interpret when does not change.
Choosing the Right Control Chart
flowchart TD
A[What type of data?] --> B{Continuous or attribute?}
B -->|Continuous| C[X‑bar & R charts]
B -->|Attribute| D{Constant sample size?}
D -->|Yes| E[NP chart]
D -->|No| F[P chart]
Summary Comparison
| Chart | Data Type | Monitors | Centre Line | Limits |
|---|---|---|---|---|
| X‑bar | Continuous | Process mean | (or ±3σ) | |
| R | Continuous | Variability (range) | ||
| P | Attribute (proportion) | Proportion defective | (vary with ) | |
| NP | Attribute (count) | Number defective | (constant ) |
Final Key Takeaways – Control Charts
- All control charts detect special‑cause variation – deviations from normal process behaviour.
- X‑bar and R charts handle continuous measurements; P and NP charts handle pass/fail data.
- Process is in control when all points lie within the limits and no non‑random patterns exist.
- Early detection of out‑of‑control signals prevents costly defects and ensures customer satisfaction.
Design of Experiments (DOE)
Design of Experiments (DOE) is a structured, systematic approach to determine the relationship between factors (independent variables) and outcomes (dependent variables). Intuitively: instead of changing one thing at a time and hoping for improvement, DOE lets you test many variables simultaneously in a carefully planned way—saving time, money, and guesswork.
Why Use DOE?
| Benefit | Explanation |
|---|---|
| Optimize product/process quality | Identify the best combination of factors (e.g., temperature, pressure, material) that yields fewer defects and higher consistency. |
| Cost reduction & resource efficiency | Fewer trials needed because multiple factors are tested together; savings in materials, labour, and production time. |
| Improve customer satisfaction | Optimise service delivery (e.g., call centre response time, store layouts) by testing variations systematically. |
| Enhance innovation & product development | Test new designs or features before launch, reducing risk of product failure and increasing market success. |
Key Concepts
- Factor – an input variable under investigation (e.g., compression force, drying time).
- Level – a specific setting or category of a factor (e.g., low/medium/high for compression; short/long for drying time).
- Treatment – a unique combination of factor levels.
- Balanced design – all treatments are tested with equal sample sizes; gives each combination equal importance.
- Full factorial experiment – tests every possible combination of all factors.
- Total treatments = product of levels of each factor:
- Example: 3 levels × 2 levels × 2 levels = 12 treatments.
- Total treatments = product of levels of each factor:
- Randomized block design – total number of experimental runs is decided first, then each run is randomly assigned to one of the treatment buckets.
Worked Example 1: Tablet Manufacturing (Pharmaceutical)
A company must ensure tablets dissolve within the required time. Key factors affecting dissolution rate:
| Factor | Levels |
|---|---|
| Compression force | Low, Medium, High |
| Drying time | Short, Long |
| Ingredient proportion | Composition A, Composition B |
Full factorial design: 3 × 2 × 2 = 12 treatment combinations. Each treatment is tested (e.g., 10 replicates each) to estimate the effect of each factor and identify the best settings.
Possible outcome: High compression force + long drying time produce the most consistent dissolution rates.
Business impact:
- Optimized tablet production → fewer defects, better regulatory compliance.
- Reduced material waste and production time.
- Avoided quality failures that could lead to recalls or customer dissatisfaction.
Worked Example 2: Email Marketing (Retail)
A retail company wants to increase customer engagement through email campaigns. Factors:
| Factor | Levels |
|---|---|
| Subject line | Short, Long |
| Discount type | Percentage off, Fixed amount off |
| Email layout | Image-heavy, Text-heavy |
DOE approach: send different combinations to separate customer subsets, tracking open rates, click-through rates, and conversions.
Possible outcome: short subject line + percentage discount + image-heavy layout yields highest engagement.
Business impact:
- Data-driven campaign optimization (instead of intuition).
- Higher ROI on marketing efforts.
- Improved customer retention through more relevant, engaging content.
Exam tip: Remember the difference between full factorial (all combinations, exhaustive) and randomized block (random assignment to a subset of combinations). Full factorial is thorough but can be expensive; randomized block is more efficient when resources are limited.
Key Takeaways
- DOE is a structured method to test multiple factors simultaneously, replacing inefficient trial-and-error.
- Factors (inputs) and levels (settings) define the experimental space; each unique combination is a treatment.
- Full factorial design tests every combination; the number of treatments equals the product of the factor levels.
- Balanced designs give equal sample size to each treatment, improving statistical reliability.
- DOE is used across manufacturing (process optimization) and services (marketing campaigns) to reduce cost, improve quality, and increase customer satisfaction.