Skip to content

Machine LearningModule 4 · Guide and practice

Module 4 · Categories, interactions, and curves

One picture: a prediction is a starting value plus a few contributions. This module changes what those contributions can be: a group adjustment, a changing slope, or a curve.

Slides → small steps → practice. Browse the original slides above each topic, or click to enlarge. Keep the formula sheet nearby.

In Module 3, the model was

Y=β0+β1X+ε.Y=\beta_0+\beta_1X+\varepsilon.

YY is the outcome; XX is an input. The intercept β0\beta_0 is the starting value. The coefficient β1\beta_1 multiplies the input. Noise ε\varepsilon is the variation the rule does not explain.

The true coefficients are unknown. We fit estimates, marked with hats, and predict without adding unknown noise:

Y^=β^0+β^1X.\widehat Y=\widehat\beta_0+\widehat\beta_1X.

With pp input columns, add their contributions:

Y^=β^0+j=1pβ^jXj.\widehat Y=\widehat\beta_0+ \sum_{j=1}^{p}\widehat\beta_jX_j.

jj selects a column; pp excludes the intercept. A column can contain a switch, a product, or a square. Least squares still chooses the weights that minimize total squared prediction error.

Categorical Inputs — original slide 4 of 6
Original slides · Categorical InputsOpen PDF ↗
Slide 4 of 6

A dummy variable, or indicator, switches a group adjustment on or off. Let D=1D=1 for a student and D=0D=0 for a nonstudent:

D={1student,0nonstudent.D=\begin{cases} 1 & \text{student},\\ 0 & \text{nonstudent}. \end{cases}

The rule is starting value + adjustment × switch:

Y^=β^0+β^1D.\widehat Y=\widehat\beta_0+\widehat\beta_1D.
GroupSubstitutePrediction
NonstudentD=0D=0β^0\widehat\beta_0
StudentD=1D=1β^0+β^1\widehat\beta_0+\widehat\beta_1

The group coded 0 is the reference or baseline. β^0\widehat\beta_0 predicts that group; β^1\widehat\beta_1 is the student-minus-nonstudent difference.

Invented example: Y^=40+15D\widehat Y=40+15D dollars. Nonstudents get 40+15(0)=4040+15(0)=40; students get 40+15(1)=5540+15(1)=55.

With only this switch and an intercept, least squares predicts each group’s sample average. With other inputs included, compare groups at the same values of those inputs.

Try it — invented: in Y^=608D\widehat Y=60-8D, D=1D=1 means premium membership. Predict for both groups. Rule: binary categories.

Show the answer

Regular: D=0D=0, so 608(0)=6060-8(0)=60. Premium: D=1D=1, so 608(1)=5260-8(1)=52. A negative adjustment lowers the prediction by 8.

3. Several categories: one baseline, the rest switches

Section titled “3. Several categories: one baseline, the rest switches”
More Categorical Inputs — original slide 2 of 4
Original slides · More Categorical InputsOpen PDF ↗
Slide 2 of 4

For Basic, Plus, and Pro plans, choose Basic as the reference. Define DPlus=1D_\text{Plus}=1 for Plus and DPro=1D_\text{Pro}=1 for Pro; otherwise each is 0.

Y^=β^0+β^PDPlus+β^RDPro.\begin{aligned} \widehat Y&=\widehat\beta_0 +\widehat\beta_P D_\text{Plus}\\ &\quad +\widehat\beta_R D_\text{Pro}. \end{aligned}

β^P\widehat\beta_P and β^R\widehat\beta_R are fitted adjustments for Plus and Pro.

PlanPlus switchPro switchPrediction
Basic00β^0\widehat\beta_0
Plus10β^0+β^P\widehat\beta_0+\widehat\beta_P
Pro01β^0+β^R\widehat\beta_0+\widehat\beta_R

KK categories need K1K-1 switches when there is an intercept. All switches are off for the reference. Coding the groups 1,2,31,2,3 instead would impose equally spaced predictions.

Invented coefficients: baseline 20, Plus adjustment 5, Pro adjustment 3-3. Predictions are 2020, 20+5=2520+5=25, and 203=1720-3=17. Plus exceeds Pro by 5(3)=85-(-3)=8.

Changing the reference changes the coefficient meanings, but preserves the fitted predictions.

Why leave one switch out?

Exactly one of all KK group switches is on in each row. They therefore add to 1, duplicating the intercept column of ones. Leaving one out lets the model separate the weights.

4. Interactions: one input changes another’s effect

Section titled “4. Interactions: one input changes another’s effect”
Interaction Terms — original slide 2 of 7
Original slides · Interaction TermsOpen PDF ↗
Slide 2 of 7

Let TT be TV spending, RR radio spending, and S^\widehat S predicted sales. An additive model gives each input a fixed slope:

S^=β^0+β^1T+β^2R.\widehat S=\widehat\beta_0+ \widehat\beta_1T+\widehat\beta_2R.

An interaction lets one input change the other’s slope. Literally calculate a new feature, TR=T×RTR=T\times R, and give it a coefficient:

S^=β^0+β^1T+β^2R+β^3TR.\begin{aligned} \widehat S&=\widehat\beta_0+ \widehat\beta_1T+\widehat\beta_2R\\ &\quad +\widehat\beta_3TR. \end{aligned}

These numbers come from slide 3 of the interaction deck. Each coefficient is a fitted multiplier; the intercept is the baseline.

TermCoefficientStd. Errort
Intercept6.75020.24827.23
TV0.01910.00212.70
Radio0.02890.0093.24
TV × Radio0.00110.00020.73

Invented inputs: take T=100T=100, R=20R=20 in the model’s input units. Use the slide’s fitted coefficients above. The new product is TR=100(20)=2000TR=100(20)=2000.

  • Intercept: start at 6.75026.7502.
  • TV contribution: 0.0191(100)=1.910.0191(100)=1.91.
  • Radio contribution: 0.0289(20)=0.5780.0289(20)=0.578.
  • Product contribution: 0.0011(2000)=2.20.0011(2000)=2.2.

Prediction = sum of the four contributions:

S^=6.7502+1.91+0.578+2.2=11.4382.\begin{aligned} \widehat S&=6.7502+1.91+0.578+2.2\\ &=11.4382. \end{aligned}

Hold RR fixed. Everything multiplying TT becomes its slope:

S^=(β^0+β^2R)+(β^1+β^3R)T.\begin{aligned} \widehat S&=(\widehat\beta_0+\widehat\beta_2R)\\ &\quad +(\widehat\beta_1+\widehat\beta_3R)T. \end{aligned} TV slope=β^1+β^3R.\text{TV slope}=\widehat\beta_1+\widehat\beta_3R.

Using the slide’s β^1=0.0191\widehat\beta_1=0.0191, β^3=0.0011\widehat\beta_3=0.0011 and our assumed R=20R=20:

TV slope=0.0191+0.0011(20)=0.0411.\text{TV slope}=0.0191+0.0011(20)=0.0411.

One extra TV unit now adds 0.0411 predicted sales units. The coefficient 0.0191 is TV’s slope only when radio spending is 0.

Similarly, radio’s slope is β^2+β^3T\widehat\beta_2+\widehat\beta_3T. A positive interaction makes either slope increase with the other input; a negative interaction decreases it.

Hierarchy principle: keep TT and RR when including TRTR, even if their individual tests are not significant. Keep the starting effects when modeling how they change.

Standard error = how much the estimate might bounce

Section titled “Standard error = how much the estimate might bounce”

Collect another sample, refit, and the coefficient will change. Std. Error, or SE, estimates the size of that sample-to-sample variation.

To test the true interaction coefficient β3=0\beta_3=0, ask: how many standard errors is the estimate from zero?

t=β^30SE(β^3).t=\frac{\widehat\beta_3-0} {\operatorname{SE}(\widehat\beta_3)}.

Use the module’s approximate two-sided rule: reject zero when t>2|t|>2; otherwise fail to reject, including at t=2|t|=2.

Here 20.73>2|20.73|>2: strong evidence of a nonzero interaction under the model’s assumptions. Statistical evidence alone proves neither causation nor improved predictions on new data.

Read rounded tables carefully. SE printed as 0.000 means a tiny positive value rounded down. It does not mean zero uncertainty. The printed values cannot reproduce the exact t-statistics.

How small is that interaction SE?

Rearrange t=β^3/SEt=\widehat\beta_3/\operatorname{SE} to get SE=β^3/t\operatorname{SE}=\widehat\beta_3/t. Using the rounded coefficient 0.0011 and reported t=20.73t=20.73 gives approximately 0.0011/20.73=0.00005310.0011/20.73=0.0000531. This is an approximate reconstruction, not the original unrounded SE.

5. Category interactions: let groups have different slopes

Section titled “5. Category interactions: let groups have different slopes”
Interaction Terms — original slide 6 of 7
Original slides · Interaction TermsOpen PDF ↗
Slide 6 of 7

First switch on a different starting value

Section titled “First switch on a different starting value”

Let XX be income, D=1D=1 for students and D=0D=0 for nonstudents. For predicted balance B^\widehat B:

B^=β^0+β^1X+β^2D.\widehat B=\widehat\beta_0+ \widehat\beta_1X+\widehat\beta_2D.

β^2\widehat\beta_2 shifts the student starting value. Both groups still have slope β^1\widehat\beta_1: parallel lines.

Add XDXD: it equals 0 for nonstudents and XX for students.

B^=β^0+β^1X+β^2D+β^3XD.\begin{aligned} \widehat B&=\widehat\beta_0+ \widehat\beta_1X+\widehat\beta_2D\\ &\quad +\widehat\beta_3XD. \end{aligned}

Substitute first; read second:

D=0:B^=β^0+β^1X,D=1:B^=(β^0+β^2)+(β^1+β^3)X.\begin{aligned} D=0:\quad\widehat B &=\widehat\beta_0+\widehat\beta_1X,\\ D=1:\quad\widehat B &=(\widehat\beta_0+\widehat\beta_2)\\ &\quad +(\widehat\beta_1+\widehat\beta_3)X. \end{aligned}

β^2\widehat\beta_2 changes the intercept; β^3\widehat\beta_3 changes the slope. At income XX, the student-minus-nonstudent gap is β^2+β^3X\widehat\beta_2+\widehat\beta_3X.

Try it — invented: B^=20+2X+10D+3XD\widehat B=20+2X+10D+3XD, with balance in dollars and income in thousands of dollars. Find both lines, then predict at X=4X=4. Rule: category interactions.

Show the answer
  • D=0D=0: B^=20+2X\widehat B=20+2X. At X=4X=4, 20+2(4)=2820+2(4)=28 dollars.
  • D=1D=1: B^=(20+10)+(2+3)X=30+5X\widehat B=(20+10)+(2+3)X=30+5X. At X=4X=4, 30+5(4)=5030+5(4)=50 dollars.

The gap rule gives 10+3(4)=2210+3(4)=22, matching 502850-28. For parallel lines, the interaction coefficient would have to be 0.

For KK groups, multiply each of the K1K-1 switches by XX to allow a separate slope per group.

6. Curves are still possible in linear regression

Section titled “6. Curves are still possible in linear regression”
Nonlinear Effects — original slide 2 of 4
Original slides · Nonlinear EffectsOpen PDF ↗
Slide 2 of 4

To model curvature, such as fuel efficiency changing with horsepower, add X2X^2 as a column:

Y^=β^0+β^1X+β^2X2.\widehat Y=\widehat\beta_0+ \widehat\beta_1X+\widehat\beta_2X^2.

This is quadratic. A cubic adds β^3X3\widehat\beta_3X^3; degree kk means powers through XkX^k.

The inputs are squared or cubed. The fitted weights still multiply known columns and add, so this remains linear regression.

Invented example: at X=2X=2, the columns [1,X,X2][1,X,X^2] become [1,2,4][1,2,4]. With weights 1,3,21,3,2:

Y^=1+3(2)+2(4)=15.\widehat Y=1+3(2)+2(4)=15.

Remember: calculate columns first; fit weights second. Extra terms can follow a real curve or random training bumps. Check new data to tell whether they help.

7. Shared practice Q4: straight line versus cubic

Section titled “7. Shared practice Q4: straight line versus cubic”
View the original practice sheet (includes solutions)
Module 3 and 4 Practice Problems - Solutions — original slide 2 of 3
Original practice sheet · Module 3 and 4 Practice Problems - SolutionsOpen PDF ↗
Slide 2 of 3

Given: 100 observations, one original input XX, and numerical outcome YY. Fit both models by ordinary least squares on the same training data:

Y^linear=a0+a1X,Y^cubic=c0+c1X+c2X2+c3X3.\begin{aligned} \widehat Y_\text{linear}&=a_0+a_1X,\\ \widehat Y_\text{cubic}&=c_0+c_1X\\ &\quad+c_2X^2+c_3X^3. \end{aligned}

aa and cc are separate fitted coefficients. RSS is the total squared miss: RSS=i(yiy^i)2\mathrm{RSS}=\sum_i(y_i-\widehat y_i)^2, using actual output yiy_i and prediction y^i\widehat y_i for observation ii.

Circle TRAIN or TEST first: training data chooses the weights; test data checks them without refitting.

  1. Linear truth: which has smaller training RSS?
  2. Linear truth: which do you expect to have smaller test RSS?
  3. Nonlinear truth: which has smaller training RSS?
  4. Nonlinear truth, amount unknown: which has smaller test RSS?

Rules: polynomial features and training versus test RSS.

The move to remember: switch off the extra terms

Section titled “The move to remember: switch off the extra terms”

Set c2=c3=0c_2=c_3=0, then c0=a0c_0=a_0 and c1=a1c_1=a_1. The cubic now copies the line exactly. Its best training fit therefore cannot be worse:

RSScubic, trainRSSlinear, train.\mathrm{RSS}_\text{cubic, train} \leq\mathrm{RSS}_\text{linear, train}.
Answer all four cases

1. Linear truth, training: cubic RSS is smaller or equal. It can copy the line and improve on it if extra terms help. Equality is possible.

2. Linear truth, test: expect the line to do better. It has the right shape already; extra terms may learn training noise. This expectation is not a guarantee for every dataset.

3. Nonlinear truth, training: cubic RSS is again smaller or equal. The ability to copy the line does not depend on what generated the data.

4. Nonlinear truth, test: not enough information. Extra terms might capture useful curvature or mostly noise. Compare on the same held-out observations, without refitting.

The cubic has p=3p=3 input columns, X,X2,X3X,X^2,X^3, and four coefficients including its intercept.

8. Shared practice Q6: fit a quadratic by renaming a column

Section titled “8. Shared practice Q6: fit a quadratic by renaming a column”
View the original practice sheet (includes solutions)
Module 3 and 4 Practice Problems - Solutions — original slide 3 of 3
Original practice sheet · Module 3 and 4 Practice Problems - SolutionsOpen PDF ↗
Slide 3 of 3

Given: fit Y^=αX2+γ\widehat Y=\alpha X^2+\gamma to (0,0)(0,0), (1,1/2)(1,1/2), and (1,3/2)(-1,3/2). Find α\alpha minimizing RSS. Here α\alpha weights X2X^2, and γ\gamma is the fitted intercept. Count p=1p=1 input column, X2X^2; there is no XX term.

Rules: transformed least squares and RSS.

Set zi=xi2z_i=x_i^2, where ii selects an observation. The model becomes a line, y^i=αzi+γ\widehat y_i=\alpha z_i+\gamma:

Supplied xix_iSupplied yiy_iCalculated ziz_i
000000
111/21/211
1-13/23/211

Squaring makes 11 and 1-1 identical inputs. Squared error favors their average output as their shared prediction.

Fast solution: two input values, two group averages

At z=0z=0: the only output is 0. Since y^=α(0)+γ=γ\widehat y=\alpha(0)+\gamma=\gamma, choose γ=0\boxed{\gamma=0}.

At z=1z=1: the average output is (1/2+3/2)/2=1(1/2+3/2)/2=1. Since y^=α(1)+0\widehat y=\alpha(1)+0, choose α=1\boxed{\alpha=1}.

Thus Y^=X2\widehat Y=X^2. This line hits both group averages, so it minimizes the total squared error.

Check RSS. At original inputs 0,1,10,1,-1, predictions are 0,1,10,1,1. Subtract predictions from the supplied outputs 0,1/2,3/20,1/2,3/2:

RSS=(00)2+(121)2+(321)2=0+14+14=12.\begin{aligned} \mathrm{RSS}&=(0-0)^2+(\tfrac12-1)^2\\ &\quad +(\tfrac32-1)^2\\ &=0+\tfrac14+\tfrac14=\tfrac12. \end{aligned}

The two outputs at z=1z=1 differ, so one shared prediction cannot hit both.

The general rule when that shortcut is unavailable

Section titled “The general rule when that shortcut is unavailable”

For nn observations, calculate averages zˉ=izi/n\bar z=\sum_i z_i/n and yˉ=iyi/n\bar y=\sum_i y_i/n. Then use the usual straight-line rules:

α=SzySzz,γ=yˉαzˉ.\alpha=\frac{S_{zy}}{S_{zz}}, \qquad \gamma=\bar y-\alpha\bar z.

The numerator measures how the columns move together; the denominator measures input spread:

Szy=i(zizˉ)(yiyˉ),S_{zy}=\sum_i(z_i-\bar z)(y_i-\bar y), Szz=i(zizˉ)2>0.S_{zz}=\sum_i(z_i-\bar z)^2>0.
Verify Q6 with the general calculation

Means: n=3n=3, new inputs 0,1,10,1,1, and supplied outputs 0,1/2,3/20,1/2,3/2 give

zˉ=0+1+13=23,yˉ=0+12+323=23.\bar z=\frac{0+1+1}{3}=\frac23, \qquad \bar y=\frac{0+\tfrac12+\tfrac32}{3}=\frac23.

Center: subtract 2/32/3 from each column:

Rowzizˉz_i-\bar zyiyˉy_i-\bar y
12/3-2/32/3-2/3
21/31/31/6-1/6
31/31/35/65/6

Multiply and add for SzyS_{zy}:

Szy=(23)(23)+(13)(16)+(13)(56)=49118+518=23.\begin{aligned} S_{zy}&=(-\tfrac23)(-\tfrac23)\\ &\quad +(\tfrac13)(-\tfrac16)\\ &\quad +(\tfrac13)(\tfrac56)\\ &=\tfrac49-\tfrac1{18}+\tfrac5{18}=\tfrac23. \end{aligned}

Square and add for SzzS_{zz}:

Szz=(23)2+(13)2+(13)2=49+19+19=23.\begin{aligned} S_{zz}&=(-\tfrac23)^2+(\tfrac13)^2+(\tfrac13)^2\\ &=\tfrac49+\tfrac19+\tfrac19=\tfrac23. \end{aligned}

Divide to find the slope: α=(2/3)/(2/3)=1\alpha=(2/3)/(2/3)=1.

Find the intercept: γ=yˉαzˉ=2/31(2/3)=0\gamma=\bar y-\alpha\bar z=2/3-1(2/3)=0. Both answers match the shortcut.

  • Group label? Switch its adjustment on or off.
  • KK groups? One reference, K1K-1 switches.
  • Product term? Group terms to read the changing slope.
  • Power of an input? Calculate the column, then fit its weight.
  • More flexible model? Training can improve; test performance must be checked.

Open the formula sheet to reuse the rules with different numbers.

Definition

Read the full glossary entry →

Module 4 formulas

Open the formula sheet →