Machine LearningMidterm practice

Midterm practice

Learn to choose a method, carry out the calculation, and explain why the answer makes sense. These are the eight problems from your practice sheet, with the same numbering. Everything you need is explained here.

Open the original questions (PDF) · Formula sheet · Mixed practice

How to study this module

  1. Try first. Read a question and write the rule you would use. Even an unfinished attempt helps you find the missing step.
  2. Use the smallest amount of help. Read the idea, then a hint if needed. Compare your work with the solution one step at a time.
  3. Close the solution and redo it. Explain the method aloud, then solve the small “Your turn” variation. Recognizing a solution is easier than producing one.
  4. Mix and revisit. Try the mixed practice at the end. Tomorrow, redo the questions you needed help with; a few days later, do the original sheet without notes.

Mark each problem on paper: needed help / solved alone / solved again later. Aim for the last category, including a correct explanation and a check on the result.

ProblemsThe skill you are practising
1, 4Identify the target, choose a class, explain core ideas
2, 7Fit a line, quantify uncertainty, test a coefficient
3, 8Read a boundary, count errors, understand ROC
5Distinguish one sequence from many possible orders
6Turn an interaction into two lines; compare model fits

Throughout: a predictor is an input, a response is the value to predict, and a hat such as y^\hat y means a fitted or predicted value. The notation N(μ,σ2)N(\mu,\sigma^2) gives a normal distribution’s mean, then variance.

Problem 1 · What are we predicting?

Try the original questions. (1) For 1,000 houses, use bedrooms, bathrooms, and school scores to understand housing prices: classification or regression, and what are nn and pp? (2) Find the Bayes classifier for the probability below, on its stated domain. (3) Are false negatives more costly than false positives in a medical setting?

p1(x)=x2−12x2+12,∣x∣≥12.p_1(x)=\frac{x^2-\tfrac12}{x^2+\tfrac12}, \qquad |x|\ge\frac1{\sqrt2}.

The idea. A regression predicts a quantity, such as a price. A classification predicts a category, such as yes/no. For classification, choosing the more probable class minimizes the chance of a mistake when both mistakes have the same cost.

Reusable rule. nn counts observations (rows); pp counts predictors (input columns). If p1(x)=P(Y=1∣X=x)p_1(x)=P(Y=1\mid X=x), choose class 1 when p1(x)≥1/2p_1(x)\ge 1/2, otherwise class 0. At an exact tie, either label has the same error; here we choose 1.

Formulas: choosing a class

Hint · Look at the response, then compare probabilities

The price is the response, not a fourth predictor. For the boundary, the denominator x2+1/2x^2+1/2 is positive, so multiplying an inequality by it keeps the inequality’s direction.

Worked solution · All three parts

1.1 — Identify the task. Price is numerical, so this is regression. There are n=1000n=1000 houses and p=3p=3 predictors: bedrooms, bathrooms, school scores. Understanding which factors are associated with price is an inference goal; it does not by itself establish causation.

1.2 — Find when class 1 is more probable. Substitute the supplied probability into p1(x)≥1/2p_1(x)\ge1/2:

x2−1/2x2+1/2≥12\frac{x^2-1/2}{x^2+1/2}\ge\frac12 ⟺2x2−1≥x2+12.\Longleftrightarrow\quad 2x^2-1\ge x^2+\frac12.

Thus x2≥3/2x^2\ge3/2. On the given domain ∣x∣≥1/2|x|\ge1/\sqrt2, the classifier is

CB(x)={1,∣x∣≥3/2,0,1/2≤∣x∣<3/2.C_B(x)= \begin{cases} 1,& |x|\ge\sqrt{3/2},\\ 0,& 1/\sqrt2\le |x|<\sqrt{3/2}. \end{cases}

Check: at x=1x=1, p1=(1−0.5)/(1+0.5)=1/3p_1=(1-0.5)/(1+0.5)=1/3, so predict 0. At x=2x=2, p1=(4−0.5)/(4+0.5)=7/9p_1=(4-0.5)/(4+0.5)=7/9, so predict 1. Do not extend the rule to the excluded middle interval: the supplied expression is not a valid probability there.

1.3 — Name what the error means. If “positive” means disease, a false negative misses someone who has the disease; a false positive flags someone who does not. True under the usual screening assumption that missing a serious disease is costlier than an unnecessary follow-up. It is not a universal fact about all medical decisions; the consequence of each error determines the cost.

When those costs differ, the usual 1/21/2 threshold need not minimize cost. With false-positive cost cFPc_{FP} and false-negative cost cFNc_{FN}, predict 1 when

p1(x)≥cFPcFP+cFN.p_1(x)\ge\frac{c_{FP}}{c_{FP}+c_{FN}}.

A larger cost for missed positives lowers the threshold.

Your turn — invented extra. You record 200 emails, four measurements per email, and a spam/not-spam label. What are the task, nn, and pp? If p1=0.4p_1=0.4, which class minimizes equal-cost error?

Check your reasoning

Classification; n=200n=200 emails and p=4p=4 predictors. Predict 0 because 0.4<0.50.4<0.5. The supplied spam label is the response, not a fifth predictor.

Problem 2 · Fit a line and measure uncertainty

Given. The model is Y=β0+β1X+εY=\beta_0+\beta_1X+\varepsilon, with noise ε∼N(0,8s2)\varepsilon\sim N(0,8s^2) and s>0s>0. The five supplied points are:

xxyy
−1−3
0−2
10
22
33

Your tasks. (2.1) Fit the intercept and slope. (2.2) Find RSS, RSE, and R2R^2. (2.3) Find 95% confidence intervals as functions of ss. (2.4) Find the values of ss for which you reject H0:β1=4H_0:\beta_1=4. (2.5) Find the values for which you cannot reject H0:β0=2H_0:\beta_0=2. Use two-sided 5% tests.

Start with the idea. A fitted line predicts a typical yy from xx. Least squares chooses the line with the smallest sum of squared vertical misses. A confidence interval asks a different question: how much would its fitted coefficients vary if we collected new noisy responses at these same xx values?

For nn observations, let xˉ\bar x and yˉ\bar y be their means. Define the horizontal spread SxxS_{xx} and joint variation SxyS_{xy}:

Sxx=∑i=1n(xi−xˉ)2S_{xx}=\sum_{i=1}^n(x_i-\bar x)^2

Sxy=∑i=1n(xi−xˉ)(yi−yˉ).S_{xy}=\sum_{i=1}^n(x_i-\bar x)(y_i-\bar y).

Products in SxyS_{xy} are positive when xx and yy move together relative to their means. Dividing that joint variation by horizontal spread turns it into a slope. The least-squares coefficients are:

β^1=SxySxx,β^0=yˉ−β^1xˉ.\hat\beta_1=\frac{S_{xy}}{S_{xx}},\qquad \hat\beta_0=\bar y-\hat\beta_1\bar x.

A residual is the observed value minus its prediction: ei=yi−y^ie_i=y_i-\hat y_i. Fit quality uses:

RSS=∑iei2,RSE=RSSn−2.\mathrm{RSS}=\sum_i e_i^2,\qquad \mathrm{RSE}=\sqrt{\frac{\mathrm{RSS}}{n-2}}.

TSS=∑i(yi−yˉ)2,R2=1−RSSTSS.\mathrm{TSS}=\sum_i(y_i-\bar y)^2,\qquad R^2=1-\frac{\mathrm{RSS}}{\mathrm{TSS}}.

RSS adds squared misses; RSE expresses a typical miss in yy units. R2R^2 compares the fitted line with always predicting yˉ\bar y.

For independent Gaussian errors with known standard deviation σ\sigma, the coefficient standard errors are:

SE(β^1)=σSxx\mathrm{SE}(\hat\beta_1)=\frac{\sigma}{\sqrt{S_{xx}}}

SE(β^0)=σ1n+xˉ2Sxx.\mathrm{SE}(\hat\beta_0)=\sigma\sqrt{\frac1n+\frac{\bar x^2}{S_{xx}}}.

Each 95% interval is the estimate ±1.96 SE\pm1.96\,\mathrm{SE}. Reject a proposed coefficient bb when:

∣β^j−b∣>1.96 SE(β^j).|\hat\beta_j-b|>1.96\,\mathrm{SE}(\hat\beta_j).

Here the supplied noise standard deviation is σ=8 s\sigma=\sqrt8\,s. Use it for the requested intervals; the RSE calculated from these five points answers part 2.2. We treat the observed xx values as fixed and assume independent errors.

Formula sheet: fitting a line · fit quality · coefficient uncertainty · hypothesis tests

Hint · Build four numbers before doing anything else

Find xˉ\bar x, yˉ\bar y, SxxS_{xx}, and SxyS_{xy}. Reuse them for both the fitted line and its standard errors. For a hypothesis test, compare the distance from the estimate to the proposed value with the interval’s half-width.

Worked solution · All five parts

2.1 · Find the fitted line

Means. There are n=5n=5 points. Their xx values sum to 5 and their yy values sum to 0, so the mean rule gives xˉ=5/5=1\bar x=5/5=1 and yˉ=0/5=0\bar y=0/5=0.

Spread and joint variation. Subtract xˉ=1\bar x=1 from each xx, giving (−2,−1,0,1,2)(-2,-1,0,1,2). Since yˉ=0\bar y=0, the centered yy values are (−3,−2,0,2,3)(-3,-2,0,2,3). Squaring the centered xx values and multiplying the matching centered pairs gives:

Sxx=4+1+0+1+4=10S_{xx}=4+1+0+1+4=10

Sxy=6+2+0+2+6=16.S_{xy}=6+2+0+2+6=16.

Slope. Divide joint variation Sxy=16S_{xy}=16 by horizontal spread Sxx=10S_{xx}=10:

β^1=1610=1.6.\hat\beta_1=\frac{16}{10}=1.6.

Intercept. The fitted line passes through (xˉ,yˉ)=(1,0)(\bar x,\bar y)=(1,0), so:

β^0=0−(1.6)(1)=−1.6.\hat\beta_0=0-(1.6)(1)=-1.6.

The answer is y^=−1.6+1.6x\hat y=-1.6+1.6x. Increasing xx by 1 increases the fitted response by 1.6.

2.2 · Measure the fit

Residuals. Substitute each supplied xx into y^=−1.6+1.6x\hat y=-1.6+1.6x, then calculate e=y−y^e=y-\hat y:

xxyyy^\hat yee
−1−3−3.20.2
0−2−1.6−0.4
1000
221.60.4
333.2−0.2

RSS. Square and add the residuals (0.2,−0.4,0,0.4,−0.2)(0.2,-0.4,0,0.4,-0.2):

RSS=0.04+0.16+0+0.16+0.04=0.4.\mathrm{RSS}=0.04+0.16+0+0.16+0.04=0.4.

RSE. We fitted two coefficients using n=5n=5 points, leaving 5−2=35-2=3 residual degrees of freedom. With RSS=0.4\mathrm{RSS}=0.4:

RSE=0.45−2≈0.3651.\mathrm{RSE}=\sqrt{\frac{0.4}{5-2}}\approx0.3651.

R2R^2. With yˉ=0\bar y=0 and observed y=(−3,−2,0,2,3)y=(-3,-2,0,2,3), the baseline squared error is:

TSS=9+4+0+4+9=26.\mathrm{TSS}=9+4+0+4+9=26.

Using RSS=0.4\mathrm{RSS}=0.4 and TSS=26\mathrm{TSS}=26:

R2=1−0.426=6465≈0.9846.R^2=1-\frac{0.4}{26}=\frac{64}{65}\approx0.9846.

The line removes about 98.46% of the squared error made by predicting the mean for these training points.

2.3 · Find the 95% confidence intervals

Slope uncertainty. The question supplies σ=8 s\sigma=\sqrt8\,s; the data give Sxx=10S_{xx}=10. Substitute into the slope standard-error rule:

SE(β^1)=8 s10=45 s.\mathrm{SE}(\hat\beta_1)=\frac{\sqrt8\,s}{\sqrt{10}}=\sqrt{\frac45}\,s.

With slope estimate β^1=1.6\hat\beta_1=1.6, its interval is:

β1: 1.6±1.9645 s\beta_1:\ 1.6\pm1.96\sqrt{\frac45}\,s

or approximately 1.6±1.7531s1.6\pm1.7531s.

Intercept uncertainty. Use σ=8 s\sigma=\sqrt8\,s, n=5n=5, xˉ=1\bar x=1, and Sxx=10S_{xx}=10:

SE(β^0)=8 s15+1210\mathrm{SE}(\hat\beta_0)=\sqrt8\,s\sqrt{\frac15+\frac{1^2}{10}}

=125 s.=\sqrt{\frac{12}{5}}\,s.

With intercept estimate β^0=−1.6\hat\beta_0=-1.6, its interval is:

β0: −1.6±1.96125 s\beta_0:\ -1.6\pm1.96\sqrt{\frac{12}{5}}\,s

or approximately −1.6±3.0364s-1.6\pm3.0364s. Larger assumed noise makes both intervals wider.

2.4 · When do we reject a slope of 4?

The fitted slope is 1.6 and the proposed slope is 4, so their distance is ∣1.6−4∣=2.4|1.6-4|=2.4. Reject when that distance exceeds the 95% half-width 1.964/5 s1.96\sqrt{4/5}\,s:

2.4>1.9645 s.2.4>1.96\sqrt{\frac45}\,s.

Since s>0s>0, this gives:

0<s<2.41.964/50<s<\frac{2.4}{1.96\sqrt{4/5}}

The upper threshold is approximately 1.3690. With enough noise, the observed slope is no longer sufficiently far from 4 to reject it.

2.5 · When can we not reject an intercept of 2?

The fitted intercept is −1.6 and the proposed intercept is 2, so their distance is ∣−1.6−2∣=3.6|-1.6-2|=3.6. We fail to reject when this distance is at most the half-width 1.9612/5 s1.96\sqrt{12/5}\,s:

3.6≤1.96125 s.3.6\le1.96\sqrt{\frac{12}{5}}\,s.

Solving for ss gives:

s≥3.61.9612/5≈1.1856.s\ge\frac{3.6}{1.96\sqrt{12/5}}\approx1.1856.

Failing to reject means the data are compatible with the proposed value at this noise level. It does not establish that the intercept equals 2. We use strict rejection outside the interval; a value exactly at an endpoint is retained.

Invented transfer check. Keep these five xx values, but add 5 to every observed yy. What happens to the fitted slope, intercept, and RSS? Predict before calculating.

Check your reasoning

The new mean is yˉ=5\bar y=5, while xˉ=1\bar x=1, Sxx=10S_{xx}=10, and Sxy=16S_{xy}=16 stay unchanged because centered yy values stay unchanged. Thus the slope remains 16/10=1.616/10=1.6, and the intercept becomes 5−(1.6)(1)=3.45-(1.6)(1)=3.4. Both observed and fitted responses rise by 5, so every residual stays unchanged and RSS remains 0.4.

Problem 3 · Turn a boundary into error counts

Try the original questions. The drawing has 13 points: red crosses are Y=1Y=1, blue circles are Y=0Y=0. The supplied probability is

P(Y=0∣X=x)=σ(2+x1−x2),P(Y=0\mid X=x)=\sigma(2+x_1-x_2),

where x1,x2x_1,x_2 are the two input coordinates and σ(z)=1/(1+e−z)\sigma(z)=1/(1+e^{-z}). (1) Draw the Bayes decision boundary. (2) Count its false negatives and false positives, and build the confusion table. (3) Repeat after flipping every prediction. (4) Find FNR and FPR if every prediction is 1.

Original drawing: seven red crosses for class 1 and six blue circles for class 0 on the x1–x2 plane.

The idea. A boundary is where the classifier is equally persuaded by both classes. A confusion table then compares what is true with what you predicted. “Positive” means class 1; “false” means the prediction was wrong.

Reusable rules. The sigmoid equals 1/21/2 at score z=0z=0 and increases with zz. Here it gives the probability of class 0, so a positive score predicts 0. Always read the event inside P(⋅)P(\cdot); the sheet’s symbol g1g_1 does not change the event.

FNR=FNTP+FN.\mathrm{FNR}=\frac{FN}{TP+FN}. FPR=FPTN+FP.\mathrm{FPR}=\frac{FP}{TN+FP}.

TPTP counts actual 1 predicted 1; TNTN counts actual 0 predicted 0; FNFN counts missed positives; FPFP counts negatives falsely flagged positive. Each rate divides by its actual class total.

Formulas: boundary and error rates

Hint · Test the origin before counting

At the origin (0,0)(0,0), the score is 2>02>0. That means P(Y=0)>1/2P(Y=0)>1/2, so this side predicts 0. Draw x2=x1+2x_2=x_1+2 through (−2,0)(-2,0) and (0,2)(0,2), then count each color on each side. None of the drawn points lies on the line.

Worked solution · Boundary, both confusion tables, and rates

3.1 — Set the two class probabilities equal. Because σ(z)=1/2\sigma(z)=1/2 exactly when z=0z=0, substitute z=2+x1−x2z=2+x_1-x_2:

2+x1−x2=0⟹x2=x1+2.2+x_1-x_2=0 \quad\Longrightarrow\quad x_2=x_1+2.

Draw the line through (−2,0)(-2,0) and (0,2)(0,2). Above the line, 2+x1−x2<02+x_1-x_2<0, so class 0 has probability below 1/21/2 and we predict 1. Below the line, predict 0. Use 1 at exact ties, as elsewhere in this module.

CB(x)={1,x2≥x1+2,0,x2<x1+2.C_B(x)= \begin{cases} 1,&x_2\ge x_1+2,\\ 0,&x_2<x_1+2. \end{cases}

Decision boundary through (−2, 0) and (0, 2), with class 1 above and class 0 below.

This sketch shows the decision rule. Use the original drawing above to count the observations.

3.2 — Count by true class first. Of the 7 red positives, 4 lie above the line (TPTP) and 3 below it (FNFN). Of the 6 blue negatives, 2 lie above the line (FPFP) and 4 below it (TNTN). The hand-drawn coordinates need not be exact to establish which side each point occupies.

Actual classPredict 1Predict 0
1 · redTP = 4FN = 3
0 · blueFP = 2TN = 4

So FN=3FN=3, FP=2FP=2. Check: 4+3+2+4=134+3+2+4=13 points, with 3+2=53+2=5 mistakes.

3.3 — Flip the predictions. CNB(x)=1−CB(x)C_{NB}(x)=1-C_B(x) changes each 1 to 0 and each 0 to 1. The actual labels stay fixed, so swap the two prediction columns:

Actual classPredict 1Predict 0
1 · redTP = 3FN = 4
0 · blueFP = 4TN = 2

Now FN=4FN=4, FP=4FP=4. Check: the original 8 correct predictions become 8 mistakes.

3.4 — Predict 1 for everyone. All 7 positives are found: TP=7TP=7, FN=0FN=0. All 6 negatives are falsely flagged: FP=6FP=6, TN=0TN=0. Substitute those counts into the rate formulas:

FNR=07=0,FPR=66=1.\mathrm{FNR}=\frac{0}{7}=0, \qquad \mathrm{FPR}=\frac{6}{6}=1.

Zero missed positives does not mean a useful classifier: this one also flags every negative.

Your turn — invented extra. A classifier finds 8 of 10 actual positives and falsely flags 3 of 15 actual negatives. Find FNR and FPR.

Check your reasoning

There are FN=10−8=2FN=10-8=2 missed positives, so FNR=2/10=0.2\mathrm{FNR}=2/10=0.2. There are FP=3FP=3 falsely flagged negatives, so FPR=3/15=0.2\mathrm{FPR}=3/15=0.2. Dividing either count by all 25 observations would answer a different question.

Problem 4 · Explain the idea before calculating

Try the original questions.

  • 4a. Find the Bayes classifier when p1(x)=1/(1+x2)p_1(x)=1/(1+x^2).
  • 4b. Explain FPR, FNR, and TPR for detecting spam.
  • 4c. Give an example of correlation without direct causation. Does correlation establish causation?
  • 4d. Does independence imply zero correlation? Does dependence imply nonzero correlation?
  • 4e. For Y=X+X2+εY=X+X^2+\varepsilon, with ε∼N(1,2)\varepsilon\sim N(1,2), find f(x)=E[Y∣X=x]f(x)=E[Y\mid X=x] and the irreducible error.
  • 4f. Use test mean squared error, MSETeMSE_{Te}, to choose flexibility.
  • 4g. Is overfitting by a very flexible model caused by high bias?
  • 4h. How do you construct a Bayes classifier? Does it minimize combined false negatives and false positives? Does it minimize false negatives alone?

The ideas and reusable rules.

Class probabilities: P(Y=k∣X=x)P(Y=k\mid X=x) means the chance of label kk for an observation with input xx. Choose the largest one when errors have equal cost. For two classes, compare p1(x)p_1(x) with 1/21/2.

Conditional average: hold X=xX=x fixed, then average the remaining randomness. For Y=h(X)+εY=h(X)+\varepsilon with noise independent of XX, noise mean μ\mu, and noise variance σ2\sigma^2,

f(x)=h(x)+μ.f(x)=h(x)+\mu. Irreducible MSE=σ2.\text{Irreducible MSE}=\sigma^2.

The predictable mean belongs in the prediction; only the unpredictable variation remains.

Correlation: it measures linear co-movement. For variables U,VU,V with finite moments,

Cov⁡(U,V)=E[UV]−E[U]E[V].\operatorname{Cov}(U,V)=E[UV]-E[U]E[V].

Correlation is this covariance divided by their standard deviations, so it is zero when covariance is zero and both standard deviations are nonzero. Zero linear co-movement need not mean no relationship.

Generalization: measure error on observations not used to fit the model. With mm evaluation observations, actual responses yiy_i, and predictions f^(xi)\hat f(x_i),

MSE=1m∑i=1m(yi−f^(xi))2.MSE=\frac1m\sum_{i=1}^{m}(y_i-\hat f(x_i))^2.

At a fixed input, expected squared prediction error separates into squared bias + variance + irreducible noise. Bias is a systematic miss in the average fitted prediction. Variance is how much that prediction changes across training samples.

Formulas: class choice · error rates · averages and dependence · model flexibility

Hint · Name the population or randomness in each part

For rates, begin with “among actual spam” or “among actual non-spam.” For noise, N(1,2)N(1,2) has mean 1 and variance 2. For independence, try a symmetric XX and the variable X2X^2. For model selection, training error and new-data error answer different questions.

Worked solution · Parts a–d

4a — Choose the more probable class. Substitute p1(x)=1/(1+x2)p_1(x)=1/(1+x^2) into p1(x)≥1/2p_1(x)\ge1/2. Since 1+x2>01+x^2>0,

11+x2≥12  ⟺  2≥1+x2\frac1{1+x^2}\ge\frac12 \iff 2\ge1+x^2   ⟺  ∣x∣≤1.\iff |x|\le1.

Therefore predict 1 on [−1,1][-1,1], and 0 outside. The endpoints are ties, assigned 1 here. Check: x=0x=0 gives probability 1; x=2x=2 gives 1/51/5.

4b — Say who is in the denominator. Let positive mean spam.

RateIn plain words
FPRAmong actual non-spam emails, the fraction incorrectly flagged as spam
FNRAmong actual spam emails, the fraction incorrectly allowed through
TPRAmong actual spam emails, the fraction correctly caught

Every actual spam email is either caught or missed, so TPR=1−FNR\mathrm{TPR}=1-\mathrm{FNR}. FPR is not the fraction of flagged emails that are innocent: that would use a different denominator.

4c — A common cause can move both variables. Hotter weather can increase both ice-cream sales and swimming activity. Sales and swimming can be correlated without sales causing swimming. Correlation alone does not establish causation. A shared cause, reverse causation, or other mechanisms can create the association.

4d — Independence is stronger than zero correlation. With finite variances, independence gives E[UV]=E[U]E[V]E[UV]=E[U]E[V], so covariance is zero. Correlation is then zero if both variances are nonzero.

The reverse fails. As a counterexample, let XX be equally likely to be −1,0,1-1,0,1 and let Z=X2Z=X^2. These are invented values to demonstrate the claim. Since XX determines ZZ, the variables are dependent. But symmetry gives

E[X]=−1+0+13=0,E[X]=\frac{-1+0+1}{3}=0, E[Z]=1+0+13=23,E[Z]=\frac{1+0+1}{3}=\frac23, E[XZ]=(−1)(1)+0+(1)(1)3=0.E[XZ]=\frac{(-1)(1)+0+(1)(1)}3=0.

Using Cov⁡(X,Z)=E[XZ]−E[X]E[Z]\operatorname{Cov}(X,Z)=E[XZ]-E[X]E[Z] gives 0−0(2/3)=00-0(2/3)=0. Both variances are positive, so the correlation is zero despite dependence.

Worked solution · Parts e–h

4e — Average the noise; keep its mean. Use the usual independent-noise assumption (the marginal distribution alone would not specify E[ε∣X=x]E[\varepsilon\mid X=x]). The supplied N(1,2)N(1,2) has mean 1 and variance 2. With h(x)=x+x2h(x)=x+x^2,

f(x)=x+x2+E[ε∣X=x]f(x)=x+x^2+E[\varepsilon\mid X=x] f(x)=x+x2+1.f(x)=x+x^2+1.

After predicting this average, the leftover error is ε−1\varepsilon-1. Its mean squared size is

E[(ε−1)2]=Var⁡(ε)=2.E[(\varepsilon-1)^2]=\operatorname{Var}(\varepsilon)=2.

Using E[ε2]=2+12=3E[\varepsilon^2]=2+1^2=3 would incorrectly count the predictable mean as unavoidable error.

4f — Compare new-data error at each flexibility. Fit each candidate using training data, calculate its MSETeMSE_{Te} on held-out observations, and select the flexibility with the lowest estimated new-data MSE. Training MSE alone can reward fitting noise.

In a practical workflow, use a validation set or cross-validation for this choice, then use a separate final test set once. Repeatedly using a “test” set to select models makes it a validation set; its minimum error is no longer an untouched final assessment.

4g — False: the issue is high variance. A very flexible model can chase accidental patterns in its training sample. On a different sample, the fitted curve may change substantially: high variance. A model too rigid to capture the pattern typically has high bias and underfits. Increasing flexibility often reduces bias while increasing variance.

4h — Choose the class with the highest conditional probability. At input xx, predicting class kk is correct with probability P(Y=k∣X=x)P(Y=k\mid X=x). Making that probability as large as possible makes the chance of error as small as possible.

With equal error costs, this minimizes expected FP+FNFP+FN on fresh observations. It does not guarantee the fewest realized mistakes on every finite sample; random outcomes can differ from expectations. It also need not minimize FNFN alone. Predicting 1 for everyone makes FN=0FN=0, but can create many false positives, as in Problem 3.

Your turn — invented extra. Let Y=3X+εY=3X+\varepsilon, with independent noise ε∼N(−2,9)\varepsilon\sim N(-2,9). What is the best squared-error prediction at X=4X=4, and what error remains unavoidable?

Check your reasoning

The conditional mean is f(x)=3x−2f(x)=3x-2. At x=4x=4, predict 3(4)−2=103(4)-2=10. The irreducible MSE is the noise variance, 9, not the standard deviation 3 and not E[ε2]=13E[\varepsilon^2]=13.

Problem 5 · One order or every order?

Try the original questions. A coin lands heads with unknown probability pp. (a) Find the probability of exactly the sequence H, H, T. (b) In 30 flips, find the probability of 20 heads and 10 tails in any order. Assume independent flips with the same pp.

The idea. Multiply probabilities along one specific sequence. If several different sequences qualify, add their probabilities. Here all sequences with the same counts have equal probability, so addition becomes “number of sequences × probability of one.”

Reusable rules. Let nn be the number of flips and hh the number of heads. Then n−hn-h is the number of tails.

P(one specified sequence)=ph(1−p)n−h.\begin{aligned} &P(\text{one specified sequence})\\ &\quad=p^h(1-p)^{n-h}. \end{aligned} P(exactly h heads)=(nh)ph(1−p)n−h.\begin{aligned} &P(\text{exactly }h\text{ heads})\\ &\quad=\binom nh p^h(1-p)^{n-h}. \end{aligned}

The count (nh)=n!/[h!(n−h)!]\binom nh=n!/[h!(n-h)!] chooses which hh of the nn positions hold heads. The factorial n!n! is n(n−1)⋯1n(n-1)\cdots1, with 0!=10!=1.

Formulas: coin sequences and counts

Hint · Does H, T, H satisfy the question?

It does not satisfy part (a), because the order differs from H, H, T. Part (b) accepts every arrangement with the requested counts, so you need a counting factor.

Worked solution · Both probabilities

5a — Multiply along the specified order. Independence lets us multiply the probabilities of H, H, and T, respectively pp, pp, and 1−p1-p:

P(H,H,T)=p⋅p⋅(1−p)P(H,H,T)=p\cdot p\cdot(1-p) =p2(1−p).=p^2(1-p).

There is no factor of 3 because only this particular order qualifies.

5b — Count qualifying orders, then multiply. One sequence with 20 heads and 10 tails has probability p20(1−p)10p^{20}(1-p)^{10}. The number of distinct arrangements is

(3020)=30!20!10!=30,045,015.\binom{30}{20}=\frac{30!}{20!10!}=30{,}045{,}015.

Those arrangements are mutually exclusive; only one order occurs. Add their equal probabilities:

30,045,015 p20(1−p)10.30{,}045{,}015\,p^{20}(1-p)^{10}.

Keep pp as a variable: the question asks for probability as a function of pp, not an estimate of the coin’s bias. As a check, if we assume p=1/2p=1/2, the result is 30,045,015/230≈0.0279830{,}045{,}015/2^{30}\approx0.02798.

Your turn — invented extra. A coin has p=0.6p=0.6. Compare the probability of H, H, T with the probability of exactly two heads in three flips.

Check your reasoning

One order: 0.62(0.4)=0.1440.6^2(0.4)=0.144. Any order: there are (32)=3\binom32=3 qualifying sequences (HHT, HTH, THH), so 3(0.144)=0.4323(0.144)=0.432.

Problem 6 · Read interactions as separate group models

Given. Let xx be GPA and gg be the supplied gender indicator: 0 for Male and 1 for Female. Salary is measured in thousands of dollars. The fitted model is:

y^=35+5x−15g+5xg.\hat y=35+5x-15g+5xg.

Your tasks. (6.a) Plot both group functions for 0≤x≤40\le x\le4. (6.b) Find when the Male prediction is higher. (6.c) Compare full training RSS after refitting with an additional x2gx^2g term. (6.d) Compare RSS using only Male training points. (6.e) Explain which comparisons change for test RSS. The extended model refits every coefficient:

y~=β~0+β~1x+β~2g\tilde y=\tilde\beta_0+\tilde\beta_1x+\tilde\beta_2g

+β~3xg+β~4x2g.\qquad+\tilde\beta_3xg+\tilde\beta_4x^2g.

Start with the idea. An interaction lets the effect of one predictor depend on another. Here xgxg switches on only when g=1g=1. Substitute the indicator before comparing the groups.

For the general model y^=b0+b1x+b2g+b3xg\hat y=b_0+b_1x+b_2g+b_3xg:

y^M=b0+b1x\hat y_M=b_0+b_1x

y^F=(b0+b2)+(b1+b3)x.\hat y_F=(b_0+b_2)+(b_1+b_3)x.

The group difference, Female minus Male, is b2+b3xb_2+b_3x. It changes with GPA when b3≠0b_3\ne0.

Adding a term expands the set of available fits. When both fits minimize unpenalized RSS on the same training data, the larger model can always set its extra coefficient to zero:

RSSlarger≤RSSsmaller.\mathrm{RSS}_{\text{larger}}\le\mathrm{RSS}_{\text{smaller}}.

This inequality concerns training RSS. Test observations were not used to choose the coefficients.

Formula sheet: interactions and nested fits

Hint · Switch the indicator off and on

Set g=0g=0 and then g=1g=1. For part 6.d, ask whether the shared-looking coefficients actually constrain the two groups to share a line. Rewrite them as one intercept and slope for each group.

Worked solution · All five parts

6.a · Plot the two regression functions

Male group. Substitute g=0g=0 into the supplied model; both terms containing gg disappear:

y^M=35+5x.\hat y_M=35+5x.

Female group. Substitute g=1g=1, combine the intercept terms 35−1535-15, and combine the slope terms 5x+5x5x+5x:

y^F=35+5x−15+5x\hat y_F=35+5x-15+5x

y^F=20+10x.\hat y_F=20+10x.

Use these calculated points to draw the two straight lines:

GPA xxMale salaryFemale salary
03520
14030
24540
35050
45560

Two predicted salary lines over GPA 0 to 4. Male salary rises from 35 to 55 thousand dollars; Female salary rises from 20 to 60 thousand dollars. They cross at GPA 3 and salary 50 thousand dollars.

At GPA 3, both models predict $50,000. These are fitted group averages, not a causal claim about gender.

6.b · Where is the Male prediction higher?

Compare the fitted functions 35+5x35+5x and 20+10x20+10x by subtraction:

y^M−y^F=15−5x.\hat y_M-\hat y_F=15-5x.

A higher Male prediction means a positive difference: 15−5x>015-5x>0, or x<3x<3. Within the requested GPA range, the answer is 0≤x<30\le x<3. The groups tie at 3; the Female prediction is higher for 3<x≤43<x\le4.

6.c · Compare total training RSS

The extended fit adds β~4x2g\tilde\beta_4x^2g. Setting β~4=0\tilde\beta_4=0 reproduces every fit available to the old model. Minimizing over this larger choice of fits therefore gives:

RSSnew, train≤RSSold, train.\mathrm{RSS}_{\text{new, train}}\le\mathrm{RSS}_{\text{old, train}}.

The new RSS is no larger. A strict decrease is not guaranteed; the extra term might provide no improvement. Although the model is quadratic in GPA for one group, it is still linear in its fitted coefficients, so ordinary least squares applies.

6.d · Compare Male training RSS

For ordinary unconstrained least squares, the Male training RSS is the same in both fits. Merely observing that x2g=0x^2g=0 for Males is not enough: the other coefficients are also refitted. The reason is that this model can fit the groups independently.

Define separate group coefficients:

aM=b0,cM=b1a_M=b_0,\qquad c_M=b_1

aF=b0+b2,cF=b1+b3.a_F=b_0+b_2,\qquad c_F=b_1+b_3.

Any two intercepts and slopes can be represented: choose b2=aF−aMb_2=a_F-a_M and b3=cF−cMb_3=c_F-c_M. Thus the original fit independently minimizes a Male line’s RSS and a Female line’s RSS. The extended fit independently minimizes a Male line’s RSS and a Female quadratic’s RSS.

The Male task is identical in both cases: minimize ∑i∈M(yi−aM−cMxi)2\sum_{i\in M}(y_i-a_M-c_Mx_i)^2. Its optimal training RSS cannot change. With at least two distinct Male GPA values, its fitted intercept and slope are also identical. This conclusion assumes unpenalized least squares with no constraints linking the group coefficients.

6.e · What changes on test data?

All groups combined: there is no guaranteed ordering of test RSS. The Female quadratic may capture useful curvature or fit training noise, so total test RSS may fall, rise, or stay equal.

Male points only: the two fits make the same Male predictions at every GPA when the Male line is identifiable (at least two distinct training GPA values). On the same Male test points, their test RSS is therefore equal too. Without an identifiable Male line, off-training predictions need not be unique, even though minimum Male training RSS is equal.

Invented transfer check. Change only the supplied interaction coefficient from 5 to 3, making the prediction 35+5x−15g+3xg35+5x-15g+3xg. Do the two group lines cross in the GPA range [0,4][0,4]?

Check your reasoning

Setting g=0g=0 gives Male salary 35+5x35+5x; setting g=1g=1 gives Female salary 20+8x20+8x. Their difference is 15−3x15-3x. Setting it to zero gives x=15/3=5x=15/3=5, outside [0,4][0,4]. The Male prediction is higher throughout the requested range. At GPA 4, the predictions are 35+5(4)=5535+5(4)=55 and 20+8(4)=5220+8(4)=52, in thousands of dollars.

Problem 7 · Separate the fitted intercept from the noise mean

Given. The model is Y=β0+β1X+εY=\beta_0+\beta_1X+\varepsilon, initially with ε∼N(0,w2)\varepsilon\sim N(0,w^2) and w>0w>0. The five supplied observations are:

xxyy
−2−3.5
−1−3
00
13
23.5

Your tasks. (7.a) Fit the intercept and slope. (7.b) Find 95% confidence intervals as functions of ww. (7.c) Find when to reject H0:β1=0H_0:\beta_1=0. (7.d) Explain what changes if the noise instead has distribution N(1,w2)N(1,w^2). Keep the printed dataset fixed in part 7.d.

Start with the idea. The fitted line estimates the average response. If the noise has a nonzero average mm, that average shifts the line’s intercept:

E[Y∣X=x]=(β0+m)+β1x.E[Y\mid X=x]=(\beta_0+m)+\beta_1x.

Here m=E[ε∣X=x]m=E[\varepsilon\mid X=x] is assumed constant. Calling the mean-response intercept α0=β0+m\alpha_0=\beta_0+m, an ordinary fitted intercept estimates α0\alpha_0. To estimate the model’s original intercept, subtract the known noise mean:

β^0=α^0−m.\hat\beta_0=\hat\alpha_0-m.

For fitting, define Sxx=∑i(xi−xˉ)2S_{xx}=\sum_i(x_i-\bar x)^2 and Sxy=∑i(xi−xˉ)(yi−yˉ)S_{xy}=\sum_i(x_i-\bar x)(y_i-\bar y). Then:

β^1=SxySxx,α^0=yˉ−β^1xˉ.\hat\beta_1=\frac{S_{xy}}{S_{xx}},\qquad \hat\alpha_0=\bar y-\hat\beta_1\bar x.

For independent Gaussian errors with supplied standard deviation ww, fixed observed xx values, and nn observations:

SE(β^1)=wSxx\mathrm{SE}(\hat\beta_1)=\frac{w}{\sqrt{S_{xx}}}

SE(α^0)=w1n+xˉ2Sxx.\mathrm{SE}(\hat\alpha_0)=w\sqrt{\frac1n+\frac{\bar x^2}{S_{xx}}}.

A 95% interval is estimate ±1.96 SE\pm1.96\,\mathrm{SE}. Subtracting a known constant mm shifts the intercept interval without changing its width.

Formula sheet: fitting a line · coefficient uncertainty · hypothesis tests · noise with a nonzero mean

Hint · Use symmetry, then identify what the intercept estimates

Both coordinate means are zero. This makes the fitted mean-response intercept zero and removes the xˉ2/Sxx\bar x^2/S_{xx} term from its variance. In part 7.d, distinguish the fitted mean-response line from the structural parameter β0\beta_0 in the model statement.

Worked solution · All four parts

7.a · Fit the coefficients

Means. The five xx values sum to 0, and the five yy values sum to 0. With n=5n=5, xˉ=0/5=0\bar x=0/5=0 and yˉ=0/5=0\bar y=0/5=0.

Spread. With xˉ=0\bar x=0, square the supplied x=(−2,−1,0,1,2)x=(-2,-1,0,1,2) values:

Sxx=4+1+0+1+4=10.S_{xx}=4+1+0+1+4=10.

Joint variation. Because both means are zero, multiply each supplied (x,y)(x,y) pair and add:

Sxy=7+3+0+3+7=20.S_{xy}=7+3+0+3+7=20.

Slope and intercept. Substitute Sxy=20S_{xy}=20, Sxx=10S_{xx}=10, xˉ=0\bar x=0, and yˉ=0\bar y=0:

β^1=20/10=2\hat\beta_1=20/10=2

β^0=0−(2)(0)=0.\hat\beta_0=0-(2)(0)=0.

The fitted line is y^=2x\hat y=2x. Here the original noise mean is zero, so the fitted intercept estimates β0\beta_0 directly.

7.b · Find the confidence intervals

Slope. The supplied noise standard deviation is ww, and Sxx=10S_{xx}=10, so SE(β^1)=w/10\mathrm{SE}(\hat\beta_1)=w/\sqrt{10}. With fitted slope 2:

β1: 2±1.96w10\beta_1:\ 2\pm1.96\frac{w}{\sqrt{10}}

or approximately 2±0.6198w2\pm0.6198w.

Intercept. Use n=5n=5, xˉ=0\bar x=0, Sxx=10S_{xx}=10, and noise standard deviation ww:

SE(β^0)=w15+0210=w5.\mathrm{SE}(\hat\beta_0)=w\sqrt{\frac15+\frac{0^2}{10}}=\frac{w}{\sqrt5}.

With fitted intercept 0, its interval is:

β0: 0±1.96w5\beta_0:\ 0\pm1.96\frac{w}{\sqrt5}

or approximately 0±0.8765w0\pm0.8765w. These use the supplied noise variance, so the normal multiplier is 1.96.

7.c · When do we reject a zero slope?

The fitted slope 2 is a distance ∣2−0∣=2|2-0|=2 from the null slope 0. Reject at the two-sided 5% level when this exceeds the half-width 1.96w/101.96w/\sqrt{10}:

2>1.96w10.2>1.96\frac{w}{\sqrt{10}}.

Solving for positive ww gives:

0<w<2101.96≈3.2268.0<w<\frac{2\sqrt{10}}{1.96}\approx3.2268.

At larger noise levels, zero falls inside the slope’s interval. A value exactly at the endpoint is retained under our strict rejection rule.

7.d · What if the noise mean is 1?

The fitted mean-response line stays the same. For the same printed observations, ordinary least squares still returns intercept α^0=0\hat\alpha_0=0 and slope β^1=2\hat\beta_1=2. Changing an assumption does not change the data’s least-squares line.

The original intercept’s interpretation changes. With the supplied new noise mean m=1m=1:

E[Y∣X=x]=(β0+1)+β1x.E[Y\mid X=x]=(\beta_0+1)+\beta_1x.

The fitted intercept 0 now estimates β0+1\beta_0+1. Subtract the known mean to estimate β0\beta_0:

β^0=α^0−1=0−1=−1.\hat\beta_0=\hat\alpha_0-1=0-1=-1.

The variance is still w2w^2. Therefore the 95% interval for the original intercept shifts down by 1 and keeps its half-width:

β0: −1±1.96w5.\beta_0:\ -1\pm1.96\frac{w}{\sqrt5}.

The slope estimate remains 2, its interval remains 2±1.96w/102\pm1.96w/\sqrt{10}, and the rejection condition remains 0<w<3.22680<w<3.2268 (approximately). The predicted average response is still y^=(−1)+2x+1=2x\hat y=(-1)+2x+1=2x.

Invented transfer check. Keep the printed data, but suppose the known noise mean is −2 and its standard deviation is w=1w=1. Find the estimate and 95% interval for the original intercept β0\beta_0.

Check your reasoning

The data still give mean-response intercept α^0=0\hat\alpha_0=0. Subtracting the known noise mean m=−2m=-2 gives β^0=0−(−2)=2\hat\beta_0=0-(-2)=2. With n=5n=5, xˉ=0\bar x=0, and w=1w=1, its standard error is 1/51/\sqrt5. The interval is 2±1.96/52\pm1.96/\sqrt5, approximately [1.1235,2.8765][1.1235,2.8765]. Its center changes; its uncertainty comes from the variance, which has not changed.

Problem 8 · Why random guessing gives a diagonal ROC

Try the original questions. A classifier ignores the input and flips an independent coin: predict 1 with probability pp and 0 otherwise. (a) Prove its ROC is a straight line as pp varies. (b) Find the AUC. (c) Without information about the input or true label, can you systematically achieve a higher or lower AUC?

The idea. An ROC curve plots the fraction of negatives you flag against the fraction of positives you catch. A useful signal lets you catch positives more often than you flag negatives. An independent coin treats both groups identically.

Reusable rules. The horizontal coordinate is the false-positive rate; the vertical coordinate is the true-positive rate. Y^\hat Y is the predicted label, and YY is the actual label.

FPR=P(Y^=1∣Y=0),\mathrm{FPR}=P(\hat Y=1\mid Y=0), TPR=P(Y^=1∣Y=1).\mathrm{TPR}=P(\hat Y=1\mid Y=1).

Vary a threshold or classifier parameter to trace the curve. AUC is the area under that curve in the unit square. One fixed value of pp gives a single operating point, not a whole curve.

Formulas: ROC and AUC

Hint · What changes when you learn the true class?

Nothing changes the coin. Whether the observation is actually positive or negative, the probability of predicting 1 is still pp.

Worked solution · The diagonal and its area

8a — Calculate each coordinate. The coin is independent of the actual label. Among actual negatives it predicts 1 with probability pp, so FPR=p\mathrm{FPR}=p. Among actual positives it also predicts 1 with probability pp, so TPR=p\mathrm{TPR}=p.

(FPR,TPR)=(p,p),0≤p≤1.(\mathrm{FPR},\mathrm{TPR})=(p,p), \qquad 0\le p\le1.

Thus the curve is TPR=FPR\mathrm{TPR}=\mathrm{FPR}, a diagonal from (0,0)(0,0) to (1,1)(1,1). For example, p=0.2p=0.2 gives (0.2,0.2)(0.2,0.2); p=0.8p=0.8 gives (0.8,0.8)(0.8,0.8).

ROC diagonal from (0, 0) to (1, 1), with the triangle beneath it shaded and labeled area one half.

8b — Find the area of the triangle. The area below that diagonal has base 1 and height 1:

AUC=12(1)(1)=12.\mathrm{AUC}=\frac12(1)(1)=\frac12.

8c — No information means no systematic ranking advantage or disadvantage. If a score or prediction is independent of the true label, positives and negatives have the same score distribution. Every threshold therefore produces equal TPR and FPR. You cannot systematically achieve a population AUC above or below 1/21/2 without information related to the label. Flipping an independent coin’s outputs still gives an independent coin.

A measured AUC on a finite random sample can be above or below 1/21/2 by chance. Also, knowing that one class is more common can help accuracy through majority guessing, but supplies no way to rank individual positives ahead of negatives; it does not improve AUC.

Your turn — invented extra. An independent random classifier flags 30% of observations. What are FPR, TPR, and FNR? Would raising that rate to 80% improve its population AUC?

Check your reasoning

With p=0.3p=0.3, FPR and TPR are both 0.3, and FNR is 1−0.3=0.71-0.3=0.7. Raising pp to 0.8 moves along the same diagonal. The family still has AUC 1/21/2.

Practice

Close the worked solutions and choose the method yourself. The questions below are invented extra exercises, not additional questions from the PDF. Try a full round, then use the feedback to decide which original problem to redo.

One successful round is a start. Redo missed questions without help tomorrow, then mix the topics again a few days later.

Can you do it without the page?

Before calling a problem learned, check that you can do all four:

  • Recognize: identify the response, probability event, or error population before choosing a formula.
  • Calculate: show the rule, substitute named values, and check the result’s sign, range, and units.
  • Explain: say why that rule fits, and name one tempting wrong approach.
  • Transfer: solve a changed version and repeat the original after a delay without notes.

For a final rehearsal, open the original sheet, keep these solutions closed, and work through all eight problems. For each miss, write one sentence: “I used ___; I should use ___ because ___.” Then redo that problem from a blank page.

Midterm practice formulas

Open the formula sheet →