Sub topic 8
How training works: parameters, loss, and optimization
This chapter assumes you can read basic Python and NumPy, know what a function and a derivative are, and understand the terms feature, label, and model from the earlier chapters. You will see how a model turns labeled examples into a set of learned numbers, and what can go wrong along the way.
What "training" means
A model is a function with adjustable numbers inside it. Training is the process of choosing those numbers so the function's outputs match the labels in the training data.
Three pieces make this work:
- Parameters are the numbers the training process adjusts. A linear model
prediction = w * x + bhas two: the weightwand the biasb. - A loss function scores how wrong the model's predictions are on the training data. Lower is better.
- An optimizer is the procedure that changes the parameters to reduce the loss.
Training is therefore a search: among all possible parameter values, find ones that give a low loss.
Parameters versus hyperparameters
Parameters are learned from data. Hyperparameters are chosen by you before training and are not changed by the optimizer. Examples are the learning rate, the number of training passes, the maximum depth of a decision tree, and max_iter in LogisticRegression.
| Kind | Who sets it | Examples |
|---|---|---|
| Parameter | The optimizer, from data | Weights, biases, tree split thresholds |
| Hyperparameter | You, before training | Learning rate, tree depth, number of clusters |
Loss functions
A loss function takes the model's prediction and the true label for one example and returns a single non-negative number. The cost (or objective) is usually the average loss over all training examples. Many texts use "loss" for both.
The right loss depends on the task.
| Task | Common loss | Formula for one example |
|---|---|---|
| Regression | Mean squared error (MSE) | `(prediction - y) ** 2` |
| Regression, robust to outliers | Mean absolute error (MAE) | `abs(prediction - y)` |
| Classification | Cross-entropy (log loss) | `-log(p_correct)` |
Squared error punishes large mistakes much more than small ones. An error of 10 costs 100, while ten errors of 1 cost only 10 in total. This makes MSE sensitive to outliers. MAE grows linearly, so a single wild point pulls the fit less.
Cross-entropy compares predicted probabilities with the true class. If the model gives the correct class probability 0.9, the loss is about 0.105. If it gives 0.01, the loss is about 4.6. A confident wrong answer is penalized heavily, and this is what you want from a probabilistic classifier.
Why not optimize accuracy directly?
Accuracy only counts right or wrong, so it changes in jumps. A tiny change to a parameter usually flips no predictions, and the optimizer gets no signal about which direction helps. Cross-entropy changes smoothly with the parameters, so it can guide the search. You still report accuracy afterward, but you train on a smooth surrogate.
Optimization by gradient descent
Imagine the loss as a landscape. Each point is a choice of parameters, and the height is the loss. Training means walking downhill.
The gradient is the vector of partial derivatives of the loss with respect to each parameter. It points in the direction of steepest increase, so the optimizer steps the opposite way:
parameter = parameter - learning_rate * gradient
The learning rate controls the step size. This single hyperparameter often decides whether training works.
A complete example from scratch
The following code trains the line w * x + b on the same kind of synthetic data used in the regression chapter. The true values are w = 3 and b = 2. Gradients of the MSE are written out by hand.
import numpy as np
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=100)
y = 3 * X + 2 + rng.normal(0, 1, size=100)
w, b = 0.0, 0.0 # initial parameters
lr = 0.01 # learning rate (a hyperparameter)
for step in range(2001):
pred = w * X + b
error = pred - y
loss = np.mean(error ** 2)
grad_w = 2 * np.mean(error * X) # d loss / d w
grad_b = 2 * np.mean(error) # d loss / d b
w -= lr * grad_w
b -= lr * grad_b
if step % 400 == 0:
print(step, round(loss, 3), round(w, 3), round(b, 3))The printed loss falls quickly at first and then flattens. w approaches 3 and b moves toward 2, though b converges more slowly. The noise in the data means the best fit is close to, but not exactly, the true values.
Choosing the learning rate
Run the same loop with several learning rates and compare the final loss.
import numpy as np
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=100)
y = 3 * X + 2 + rng.normal(0, 1, size=100)
def train(lr, steps=200):
w, b = 0.0, 0.0
for _ in range(steps):
error = (w * X + b) - y
w -= lr * 2 * np.mean(error * X)
b -= lr * 2 * np.mean(error)
return np.mean(((w * X + b) - y) ** 2)
for lr in (0.001, 0.01, 0.05):
print(lr, f"{train(lr):.3g}")You should see three different behaviors:
0.001: the loss is still high after 200 steps. Steps are too small, so training is slow.0.01: the loss is near its floor. This is a good setting for this data.0.05: the loss is enormous. Each step overshoots the minimum and lands higher on the other side, so the error grows with every update. This is divergence.
For this problem, the largest stable rate is roughly 0.03. It depends on the scale of the features, which is one reason features are often standardized before training.
Variants of gradient descent
The loop above uses every training example to compute each gradient. This is batch gradient descent. Real systems usually use one of two variants.
- Stochastic gradient descent (SGD) computes the gradient from one example per update. Updates are cheap but noisy.
- Mini-batch gradient descent uses a small group, such as 32 or 256 examples. It balances noise and speed, and it fits well on modern hardware. Most deep learning uses this.
One full pass through the training set is an epoch. Training for 10 epochs with a batch size of 50 on 1,000 examples means 200 parameter updates.
Optimizers such as Adam and momentum methods adapt the step size or smooth the direction. They are refinements of the same idea: compute a gradient, then step.
Not every model uses gradient descent
Gradient descent is common but not universal.
LinearRegressionin scikit-learn solves the least-squares problem directly with linear algebra. There is no learning rate.LogisticRegressionuses a quasi-Newton method (L-BFGS by default) and stops aftermax_iteriterations. If it has not converged by then, scikit-learn raises aConvergenceWarning.DecisionTreeClassifierpicks splits greedily, choosing at each node the split that most reduces an impurity measure. This is a loss-driven search, but it has no gradient.
Convexity, local minima, and initialization
For linear regression with MSE, the loss surface is a single bowl. Any downhill path reaches the one global minimum, so the starting point does not matter. Logistic regression with cross-entropy is also convex.
Neural networks are not convex. Their loss surfaces have many flat regions and local minima. Results can depend on the random starting weights, which is why you fix a random seed when you want repeatable runs. Different seeds can give slightly different models of similar quality.
Common errors
- Forgetting to scale features. If one feature ranges from 0 to 1,000,000 and another from 0 to 1, a single learning rate suits neither. Gradient descent zigzags or diverges. Standardize features first.
- Stopping too early or too late. Too few iterations leaves the model underfit. Training far past the point where validation loss stops improving can contribute to overfitting. The next chapter covers this.
- Watching only the training loss. Training loss almost always keeps falling. A low value does not show the model works on new data.
- Ignoring warnings about convergence. A
ConvergenceWarningmeans the optimizer ran out of iterations. Increasemax_iteror scale the features. - Choosing a loss that does not match the goal. Using MSE on a task with heavy outliers, or predicting class labels as numbers with a regression loss, optimizes the wrong thing.
Summary of the working model
Training takes a model with adjustable parameters and a loss function that measures its errors on labeled data. An optimizer repeatedly adjusts the parameters to reduce that loss. The learning rate, batch size, and number of iterations are hyperparameters that you choose. A low training loss is the optimizer's target, not proof of a good model, and that is the problem generalization addresses in the next chapter.
Exercise
You train a regression model by gradient descent and watch the training loss. It increases on every step and eventually becomes inf. Name the most likely cause and two things you could change.
Show answer
The learning rate is too large, so each update overshoots the minimum and the error grows (divergence). You could lower the learning rate, for example by a factor of 10, and standardize the input features so no single feature dominates the gradient.
Exercise
Why do we usually train a classifier with cross-entropy instead of directly minimizing the number of misclassified examples?
Show answer
The count of misclassified examples changes in sudden jumps, so a small parameter change usually gives the optimizer no usable signal. Cross-entropy changes smoothly with the parameters and has a gradient, so the optimizer can tell which direction reduces it. Accuracy is still used for evaluation afterward.
Exercise
A dataset has 1,200 training examples. You train with mini-batches of 100 for 15 epochs. How many parameter updates happen?
Show answer
180. Each epoch has 1,200 / 100 = 12 updates, and 12 * 15 = 180.