In ordinary programming, we supply the rule that turns inputs into answers.
In supervised learning, example inputs and answers help us learn a rule.
A detailed theory can be difficult to work out. Could we learn the relationship from measured examples?
We can fit different curves to the measured inputs and outputs. Which one should we trust?
This curve describes the readings we used to fit it. That alone does not show how well it predicts new readings.
Keep the curve fixed, then compare its predictions with readings it did not fit.
Classification and regression use example targets. Dimensionality reduction can learn from the inputs alone.
Can we separate these two species using petal length and petal width?
\[ z=w_l x_l+w_w x_w+b \]
A score of zero marks the straight boundary.
The circled virginica has label +1, but its score is -0.048. Which way should its score move?
\[ w\leftarrow w+\eta yx,\qquad b\leftarrow b+\eta y \]
For this example, the score changes from -0.048 to 0.234. Other predictions can change too.
A looks strongly versicolor, B strongly virginica, and C is near the overlap. Should our predictions be equally confident?
\[ p(y=1\mid x)=\frac{1}{1+e^{-z}} \]
The sigmoid converts a linear score into a probability. Labels are now 0 and 1.
The population has 50 virginica and 50 versicolor flowers. A flower falls on the virginica side. How likely is it to be virginica?
\[ P(V\mid\mathrm{side})=\frac{47}{47+3}=0.94 \]
Now there are 450 virginica and 50 versicolor. The same rule puts 423 virginica and 3 versicolor on that side.
\[ P(V\mid\mathrm{side})=\frac{423}{423+3}\approx0.993 \]
| Same side rates | First population | Second population |
|---|---|---|
| Prior P(virginica) | 50% | 90% |
| P(virginica | side) | 94% | 99.3% |
\[ P(V\mid S)=\frac{P(S\mid V)P(V)}{P(S\mid V)P(V)+P(S\mid\neg V)P(\neg V)} \]
The meaning of the observed evidence depends on how common each class was before seeing it.
The true label is 1. At a cutoff of 0.5, p = 0.01 and p = 0.49 are both wrong. Should they receive the same penalty?
\[ \ell=-y\ln p-(1-y)\ln(1-p) \]
A confident mistake receives a much larger loss.
\[ J=\frac{\ell_1+\ell_2+\cdots+\ell_N}{N} \]
\[ J=\frac{1}{N}\sum_{i=1}^{N}\ell_i \]
A mean loss describes the predictions across a set of examples. Training can also include a regularisation penalty.
The forward pass calculates predictions and loss. The backward pass applies the chain rule to calculate gradients.
\[ \theta_{\mathrm{new}}=\theta-\eta\frac{\partial J}{\partial\theta} \]
Move parameters against their local cost slopes. Then calculate the next predictions using the changed parameters.
| Term | Meaning for iterative training |
|---|---|
| Batch | Examples used together to calculate an update. |
| Step | One parameter update. |
| Epoch | One complete pass through the training examples. |
The learning rate controls the scale of a step.
Too small: slow progress. Goldilocks: useful steps. Too large: repeated overshooting can move us away from the minimum.
Would more epochs be your first response in both cases?
Both high: compare with an attainable reference, then check optimisation, representation and capacity.
A persistent gap: check the split and data, then consider excessive flexibility or limited training information.
| Decision | Data role |
|---|---|
| Fit weights, axes or reference information | ? |
| Choose a model or checkpoint | ? |
| Evaluate the frozen choice | ? |
| Decision | Data role |
|---|---|
| Fit weights, axes or reference information | Training |
| Choose a model or checkpoint | ? |
| Evaluate the frozen choice | ? |
| Decision | Data role |
|---|---|
| Fit weights, axes or reference information | Training |
| Choose a model or checkpoint | Validation |
| Evaluate the frozen choice | ? |
| Decision | Data role |
|---|---|
| Fit weights, axes or reference information | Training |
| Choose a model or checkpoint | Validation |
| Evaluate the frozen choice | Test |
Preprocessing learns from training data too. Validation and test examples reuse those fitted steps.
Each fit uses 12 data points. The thin curves show how the fitted model changes across repeated noisy samples.
More data points can decrease variance. Each fit now uses 80 readings. The straight model still cannot follow the curve.
| Flagged | Not flagged | |
|---|---|---|
| Actual defect | 8 true positives | 2 false negatives |
| Actual clear | 3 false positives | 7 true negatives |
\[ \mathrm{Recall}=\frac{8}{8+2}=0.80\qquad\mathrm{Precision}=\frac{8}{8+3}=0.73 \]
| Flagged | Not flagged | |
|---|---|---|
| Actual defect | 10 true positives | 0 false negatives |
| Actual clear | 7 false positives | 3 true negatives |
\[ \mathrm{Recall}=\frac{10}{10+0}=1.00\qquad\mathrm{Precision}=\frac{10}{10+7}=0.59 \]
| Flagged | Not flagged | |
|---|---|---|
| Actual defect | 4 true positives | 6 false negatives |
| Actual clear | 1 false positives | 9 true negatives |
\[ \mathrm{Recall}=\frac{4}{4+6}=0.40\qquad\mathrm{Precision}=\frac{4}{4+1}=0.80 \]
Each cutoff gives one pair of rates. Sweeping through all cutoffs traces the full ROC curve.
Each fold learns its own preprocessing and model from its training portion. Compare settings on the same folds.
These beam measurements have known labels. Could one straight line enclose all the accepted readings?
\[ \phi=(\mathrm{Horizontal\ beam\ offset})^2+(\mathrm{Vertical\ beam\ offset})^2 \]
This is the squared distance from the target centre. A single cutoff on that value could decide whether the offset is acceptable.
\[ \mathrm{Accept\ if}\quad\phi\leq1.3^2=1.69\ \mathrm{mm}^2 \]
We have temperature, vibration and the known outcome for each part. What questions could separate the labels?
Successive questions divide the inputs into regions. During fitting, the tree chooses useful questions from labelled examples.
This small example needs two threshold questions. Their leaves create the rectangular decision regions.
The trees see different training samples. What do they predict for the same marked point P?
\[ P(\mathrm{defect}\mid P)=\frac{0+1+1}{3}\approx0.67 \]
Average the class probabilities, then choose the class.
Different training samples and feature choices produce varied trees. Their average can be less sensitive to one particular fitted tree.
An SVM balances a wide separating margin against costly violations. A soft margin allows exceptions.
At prediction time, find nearby stored training examples and use their labels to vote.
Small k can follow individual examples. With k equal to the whole reference set, the same majority wins everywhere.
Expressing measurements in training standard deviations changes their relative numerical influence on a distance rule.
“Nearest” can be only slightly closer than typical examples. Useful structure and a suitable representation still matter.
At 0°, the projected sample variance is 4.00 °C². Could another direction keep more?
At 20°, the projected sample variance is 6.37 °C². Could another direction keep more?
At 70°, the projected sample variance is 6.37 °C². Could another direction keep more?
At 45°, the projected sample variance is 7.68 °C². This direction keeps 96% of the original variance.
Which direction varies most? Which distinguishes these illustrative flower species?
The retained length coordinate preserves over 99% of the variance but loses the width distinction between species.
Hidden units transform the input. The output combines those learned responses, and one loss trains both sets of weights.
Without nonlinear activations, stacked affine layers still give one affine map. With them, the feature map can bend.
Could one straight line separate the two positive corners from the negative corners?
Two threshold-like responses can select the middle band. A nonlinear representation changes the possible decision regions.
Forward calculations produce an output. Backpropagation carries loss gradients through every layer, then the optimiser updates the parameters.
The same filter reads many image patches. Training learns which local responses help the task.
An existing image feature extractor can support a new output head. Check the new task and input convention with representative examples.
| Approach | Idea |
|---|---|
| SGD | Use the current gradient estimate. |
| Momentum | Accumulate a direction across updates. |
| AdaGrad / RMSProp | Use gradient history to adjust parameter scales. |
| Adam | Combine a moving direction with adaptive scaling. |
The optimiser changes the route through parameter space. Validation still decides whether the resulting model is useful.
Weight penalties, capacity choices and validation-based early stopping can constrain the fitted solution.
| Method | What is fitted or retained |
|---|---|
| Logistic / neural models | Weights and biases. |
| Trees and forests | Split rules and leaf predictions. |
| Nearest neighbours | Reference examples and a search structure. |
| PCA | Means and projection directions. |
A shared prediction workflow does not mean every method uses backpropagation.
| Observation | A useful first question |
|---|---|
| Poor training and validation fit | Have we checked optimisation, representation and capacity? |
| Excellent training, weaker validation | How specific or sample-sensitive is this fit? |
| Good held-out score, poor new inputs | Does the evaluation represent the intended use? |
We will now use this reasoning in one complete investigation.
| Training row | x₂₈ | x₃₆ | x₄₄ | Other inputs | Label |
|---|---|---|---|---|---|
| Example 1 | 4 | 0 | 0 | … | 9 |
| Example 2 | 16 | 15 | 15 | … | 1 |
| Example 3 | 15 | 12 | 13 | … | 8 |
| Example 4 | 1 | 12 | 9 | … | 4 |
There are 64 numerical inputs and a supplied label from 0 to 9. Can we predict the label on new rows?
Here the 64 measurements are the pixels of an 8 × 8 image. The label tells us which digit it represents.
We will also test a small position change after freezing the model.
There is variation within a label as well as differences between labels. Each image still supplies the same 64 pixel coordinates.
Use the same training and validation rows for all three experiments. Keep the final test set outside these choices.
Always predicting the most common training label would get 36/360 validation images right.
That is about 10%. Our first learned model should demonstrate much more than this.
linear = make_pipeline(
StandardScaler(),
LogisticRegression(C=1, solver="lbfgs",
max_iter=2000, random_state=8)
)
linear.fit(X_train, y_train)
With ten labels, this fits ten linear class scores and converts them to probabilities with softmax.
\[ z_k=\sum_{j=1}^{64}w_{kj}\widetilde{x}_j+b_k,\qquad k=0,\ldots,9 \]
\[ P(y=k\mid x)=\frac{e^{z_k}}{\sum_{c=0}^{9}e^{z_c}} \]
This is one two-dimensional slice of the fitted 64-input model. Where two class scores tie, their boundary is straight.
The prepared input coordinates may already contain useful class structure.
Hypothesis: a simple linear baseline can recognise many examples. We will measure how well it generalises.
What should we examine besides the training score?
| Model | Train correct | Validation correct | Validation loss |
|---|---|---|---|
| Linear model | 1,075 / 1,077 | 346 / 360 | 0.115 |
Read an off-diagonal cell as an observed digit receiving another label.
Some errors are uncertain; others assign high probability to the wrong class.
Hypothesis: learned pixel combinations may fix mistakes that linear class scores leave behind.
A tree can learn successive brightness questions, creating a more flexible decision rule.
The training fit is already very strong. Extra flexibility also risks overfitting, so validation must decide.
tree = DecisionTreeClassifier(random_state=8)
tree.fit(X_train, y_train)
Let the tree choose its splits without an explicit depth limit.
Each input follows the questions until it reaches a leaf with class probabilities.
The tree gets 1,077/1,077 training images right.
Have we solved the problem?
| Model | Train correct | Validation correct | Validation loss |
|---|---|---|---|
| Linear model | 1,075 / 1,077 | 346 / 360 | 0.115 |
| Single tree | 1,077 / 1,077 | 302 / 360 | 5.807 |
This tree has depth 13 and 117 leaves.
It reproduces the training labels perfectly but makes more mistakes on the validation examples.
The gap motivates checking how sensitive the fitted rules are to the particular training sample.
Refit the same learner on three bootstrap samples of the training rows. Their predictions can disagree.
Could different trees compensate for some of one another’s sample-specific choices?
forest = RandomForestClassifier(
n_estimators=300, max_features="sqrt", random_state=8
)
forest.fit(X_train, y_train)
Bootstrap the training rows, vary the features considered at splits, then average the trees’ class probabilities.
| Model | Train correct | Validation correct | Validation loss |
|---|---|---|---|
| Linear model | 1,075 / 1,077 | 346 / 360 | 0.115 |
| Single tree | 1,077 / 1,077 | 302 / 360 | 5.807 |
| Random forest | 1,077 / 1,077 | 351 / 360 | 0.331 |
| Validation measure | Linear model | Forest |
|---|---|---|
| Correct labels | 346 / 360 | 351 / 360 |
| Mean cross-entropy | 0.115 | 0.331 |
| Model structure | 10 linear class scores | 300 trees |
The forest gets five more labels right here. The linear model has the lower probability loss.
Which result matters depends on the purpose of the predictions.
Selected model: Random forest. It has the highest validation accuracy among the three candidates.
The primary goal here is to return the correct digit label. If probability loss were the priority, the comparison would favour the linear model.
The trained forest and its choices are now fixed.
| Frozen forest | Result |
|---|---|
| New test images | 360 |
| Correct labels | 351 / 360 |
| Accuracy | 97.5% |
| Mean cross-entropy | 0.357 |
These are different images from the validation set. The equal correct count is a coincidence.
The forest works well on held-out, prepared images from this collection.
A random image split does not establish performance on new writers, phone cameras or differently prepared crops.
The claim must stay within the scope of the evidence.
The same digit moves by one column. Should the chosen model’s answer stay the same?
The digit is still a 3. The fixed forest now predicts 9.
The same 325 test images are scored before and after the shift. No digit strokes were removed.
The validation winner is sensitive to a small change in position.
Would adding more trees address the cause, or should we first investigate the inputs and how they are prepared?
These are proposed next experiments. They have not been demonstrated to fix the problem here.
| Observation | What we learned here |
|---|---|
| Linear baseline: 346/360 | The prepared pixel coordinates already support a strong simple model. |
| Single tree: 302/360 | A perfect training fit can leave a much weaker validation fit. |
| Forest: 351/360 | Combining varied trees helps here, while accuracy and loss still disagree. |
The position check then shows a weakness of this fitted forest on its raw pixel inputs.
Keep the question, the measured result and the next decision connected. An unsuccessful change can still teach you something useful.
For this frozen forest, a new input must supply the same 64 pixel coordinates in the same order and numerical convention.