Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Basic

Metrics

Expected MSE

For a continuous outcome, prediction error comes from systematic error, sensitivity to the training sample, and noise in the new outcome.

E[(y0−f^(x0))2]=[Bias⁡(f^(x0))]2+Var⁡(f^(x0))+Var⁡(ϵ0)E\big[(y_0-\hat f(x_0))^2\big]=\big[\operatorname{Bias}(\hat f(x_0))\big]^2+\operatorname{Var}(\hat f(x_0))+\operatorname{Var}(\epsilon_0)
ComponentMeaning
BiasHow far the average fitted prediction is from the true function: E[f^(x0)]−f(x0)E[\hat f(x_0)]-f(x_0).
VarianceHow much the fitted prediction changes across new training samples.
NoiseVariation in a new outcome that remains even if the true function is known.

We want both low bias and low variance. Irreducible noise sets a lower bound on prediction error.

What is being averaged?

Write y0=f(x0)+ϵ0y_0=f(x_0)+\epsilon_0, with E(ϵ0∣x0)=0E(\epsilon_0\mid x_0)=0. Hold x0x_0 fixed and refit the same method on new training samples. The fitted values f^(x0)\hat f(x_0) change across those samples; the new observation also has its own noise.

The decomposition assumes that the new observation’s noise is independent of the training sample. If noise variance changes with xx, use Var⁡(ϵ0∣x0)\operatorname{Var}(\epsilon_0\mid x_0). This is a squared-error result; classification error does not have the same decomposition.

<IPython.core.display.Image object>

Accuracy

Predicted TruePredicted False
Actual TrueTPFN
Actual FalseFPTN
  • Used for Categorical problems.

  • Refers to the percentage of correctly identified observations.

TP + TNn,n=Total Number of Observations\frac{\text{TP + TN}}{n}, n=\text{Total Number of Observations}
1n∑i=1nI(yi=yi^)\frac{1}{n}\sum^n_{i=1} I(y_i=\hat{y_i})

Sensitivity and Specificity

Sensitivity

Share of actual positives correctly identified. Also called the true-positive rate or recall.

TPR=TPTP+FN\mathrm{TPR}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}

Its denominator includes all actual positives; missed positives reduce sensitivity.

Specificity

Share of actual negatives correctly identified. Also called the true-negative rate.

TNR=TNTN+FP\mathrm{TNR}=\frac{\mathrm{TN}}{\mathrm{TN}+\mathrm{FP}}

Its denominator includes all actual negatives. The false-positive rate is 1−specificity1-\mathrm{specificity}.

We want high sensitivity and high specificity, but changing the classification threshold usually trades one against the other.

Multi-Class Classification

  • Precision/recall must be evaluated for each class when there are multiple classes.

  • Macroaveraging:

    1K∑k=1KPrecisionk\frac{1}{K}\sum^K_{k=1}\text{Precision}_k
    • Each classes get equal weights during evaluation. By ignoring class size, gives rare categories the same weight as frequent categories.

    • E.g., Computing FF-values for each 2,2 classification table and averaging the FF-values afterwards.

  • Microaveraging:

    • Aggregate all predictions first, then compute the metric.

    • Sum all TP, FP, FN across classes.

    • Gives more weight to large classes.

    • Useful when we care about the overall accuracy, and when the data is imbalanced.

    • Compute the metric after pooling TP, FP, and FN; averaging class-specific scores instead would be macroaveraging.

    • E.g., Pooling all the 2,2 tables into a single 2,2 table and computing FF-values based on the pooled tbable.

ROC

A receiver operating characteristic (ROC) curve shows how the true-positive and false-positive rates change as the classification threshold moves.

<IPython.core.display.Image object>
AxisWhat it measures
HorizontalFalse-positive rate: FP/(FP+TN)\mathrm{FP}/(\mathrm{FP}+\mathrm{TN}), or 1−specificity1-\text{specificity}.
VerticalTrue-positive rate: TP/(TP+FN)\mathrm{TP}/(\mathrm{TP}+\mathrm{FN}), also called recall or sensitivity.

Points near the upper-left corner combine high sensitivity with a low false-positive rate.

Constructing the curve

01 / Order

Sort observations by predicted probability of the positive class.

02 / Threshold

At each cutoff, classify observations at or above it as positive and those below it as negative.

03 / Plot

Calculate FPR and TPR at each cutoff, then plot the resulting points.

F-Measure

F₁ combines precision and recall. It does not reward correct negative predictions, so a large number of true negatives cannot inflate the score. Values range from 0 to 1, with higher values indicating a better precision–recall balance.

F1=2TP2TP+FP+FN=2Precision⋅RecallPrecision+RecallF_1=\frac{2\mathrm{TP}}{2\mathrm{TP}+\mathrm{FP}+\mathrm{FN}}=2\frac{\mathrm{Precision}\cdot\mathrm{Recall}}{\mathrm{Precision}+\mathrm{Recall}}
MetricQuestion
PrecisionHow many predicted positives are correct? TP/(TP+FP)\mathrm{TP}/(\mathrm{TP}+\mathrm{FP}).
RecallHow many actual positives are found? TP/(TP+FN)\mathrm{TP}/(\mathrm{TP}+\mathrm{FN}).

Useful when

The positive class matters, and you need one summary of precision and recall. Examples include fraud detection and disease screening, where positives may be rare.

Check first

F₁ gives precision and recall equal importance. If false positives and false negatives have different costs, examine them separately and choose a threshold using those costs.

With balanced classes and symmetric error costs, accuracy may also be useful. RMSE applies to numerical prediction, rather than class labels. Emphasize precision to limit false positives, and recall to limit missed positives.

Choosing a threshold

If a false positive costs CFPC_{FP} and a false negative costs CFNC_{FN}, the expected costs at a point with probability pp are

predict 1: CFP(1−p),predict 0: CFNp.\text{predict 1: } C_{FP}(1-p),\qquad \text{predict 0: } C_{FN}p.

With zero cost for correct decisions, predict 1 when

p>CFPCFP+CFN.p>\frac{C_{FP}}{C_{FP}+C_{FN}}.

This calculation needs probabilities that reflect the population where predictions will be used. A good AUC only establishes good ranking; it does not establish that a predicted probability of 0.8 is reliable.

Baseline

Bayes Classifier

Pr⁡(Y=j∣X)\Pr(Y = j \mid X)
  • A baseline model with an assumption that test errors are minimized when each new observation is assigned to the most likely class.

  • For a new observation, choose the class with the largest probability.

<IPython.core.display.Image object>
  • From the graph above, there are two noticeable boundaries where can lead to a change of membership to a new observation, one at 0 and the other at 8.

  • Error rate (For a given observation xx): 1−maxjPr⁡(Y=j∣x)1-\text{max}_j\Pr(Y=j|x)

  • Error rate (Overall Bayes error rate): 1−E(maxjPr⁡(Y=j∣x))1-E(\text{max}_j\Pr(Y=j|x))

    • The Bayes error rate is the minimal error rate.

    • However, in practice, Bayes error rate is never known, because the underlying functions are not known.

Overfitting and Underfitting

Overfitting

  • Overfitting happens when the model fits random noise of a sample rather than the generalizable relationship.

  • When does it happen?

    • When the model has too many parameters relative to the number of observations.

    • This is why advanced machine learning algorithms must be watchful towards overfitting; they are designed to have a lot of parameters.

    • When the model is too flexible; when a model can fit a wide variety of shapes and patterns in the data.

<IPython.core.display.Image object>
  • As can be seen on the graph above, overfitted model can twist and bend very closely on data.

Underfitting and validation

An underfitted model misses a pattern that is present in the data. Both training and validation errors can remain high. An overfitted model often has low training error but noticeably higher validation error. The gap is useful evidence, although different training and validation populations can also cause a gap.

Use the training set to estimate parameters and a validation set, or cross-validation within the training data, to choose model settings. Keep the test set for evaluating the chosen procedure. Trying many settings on the test set gradually makes it part of model selection.

In KK-fold cross-validation, each fold is held out once while the other K−1K-1 folds are used for fitting. Preprocessing must also be fitted again within each training fold. For repeated measurements, keep observations from the same subject together. For future prediction, use splits that preserve time order.

Tips

Log Transformation

  • When yy or any variable spans multiple magintude, it is easier to take a log of it. (E.g., log(y)log(y))

    • Log transformation reduces the scale of very large values more than small ones.

    • E.g.:

    • y=10y = 10 → log(y)=2.3log(y) = 2.3

    • y=1,000,000y = 1,000,000 → log(y)=13.8log(y) = 13.8

    • Hence, log transformations can shrink gaps dramatically, and prevent large values from dominating the model.

    • Can reduce right skewness of a positive variable and make some relationships easier to model; improvement is not guaranteed. A logarithm needs positive inputs, and back-transforming a prediction of log response does not generally give the mean response.

Nonlinear models

  • A model is nonlinear if parameters (β\beta) appear nonlinearly, not the predictors (xix_i). For example,

    y=β11+eβ2xy = \frac{\beta_1}{1+e^{\beta_2x}}

    ... is nonlinear, because you cannot seperate β1\beta_1 and β2\beta_2 into a clean linear combination. For example, neural networks have their weights interacting across layers and are an example of nonlinear model.

ExampleLinear in coefficients?
Linear regressionβ0+β1x2\beta_0 + \beta_1 x^2Yes
Logistic regression11+e−(β0+β1x)\frac{1}{1+e^{-(\beta_0 + \beta_1 x)}}Yes (in log odds)
Nonlinear modelβ1eβ2x\beta_1 e^{\beta_2 x}No

Linear Model

y=β0+β1x1+β2x2+...βpxpy = \beta_0 + \beta_1x_1 + \beta_2x_2 + ... \beta_px_p
  • This model above is called as ordinary linear regression (OLR).

  • Least squares gives the best linear unbiased estimator under the Gauss–Markov assumptions: a correctly specified linear conditional mean, full column rank, and errors with zero conditional mean, constant variance, and no correlation.

    • AKA, has the lowest variance.

    • Refers to a specific way to esimate the coefficients β\beta.

    • Chooses β^\hat{\beta} by minimizing: RSS=∑(yi−yi^)2\text{RSS} = \sum(y_i-\hat{y_i})^2.

Hyperparameter and Parameter

Parameter

A value estimated from training data when fitting the model.

Examples

  • Regression coefficients β\beta.

  • Weights in logistic regression and neural networks.

Hyperparameter

A setting that controls the model or fitting procedure. Choose it before an individual fit, often by comparing validation results across fits.

Examples

  • kk in kk-NN.

  • λ\lambda in ridge and LASSO regression.

  • max_depth in tree models.

  • learning_rate in boosting.