Model Training and Evaluation: Loss, Overfitting, and Accuracy
Model Training and Evaluation: Loss, Overfitting, and Accuracy
Search
Ask the AI

Model Training and Evaluation: Loss, Overfitting, and Accuracy

Evaluating a model requires understanding what training adjusts, what a loss function measures, why overfitting happens, and why test data must stay separate. Accuracy is one part of that evaluation.

This article explains the basics of model training and evaluation: parameters, loss functions, epochs, overfitting, validation data, test data, and common classification metrics.

If the previous article explained how to organize a machine learning project, this one explains how to decide whether the training process is trustworthy.

1. What Does Training Adjust?

A model can be viewed as a function with parameters:

prediction = model(input_features, parameters)

The discussion below concerns supervised parameterised models. Training estimates parameters according to a chosen loss or fitting rule; separate validation checks how the fitted model generalises.

A very simple linear model looks like this:

y = w1 * x1 + w2 * x2 + b

Here, w1, w2, and b are parameters. Training tries to find better values for them.

2. What Is a Loss Function?

The model needs a way to measure how wrong a prediction is. That measurement is the loss function.

For regression, a simple loss can be squared error:

loss = (y_true - y_pred) ** 2

For classification with one hard target class, cross-entropy is the negative log of the predicted probability assigned to that class. Its basic intuition is:

A confidently wrong prediction receives a large loss. A prediction close to the correct answer receives a smaller loss.

During training, the algorithm tries to reduce the overall loss.

3. The Intuition Behind Gradient Descent

Many models use gradient descent or a variant of it to update parameters. Think of it as walking downhill:

  1. The current parameters produce a loss value
  2. The algorithm estimates which direction reduces loss
  3. The parameters move a small step in that direction
  4. The process repeats many times

An important hyperparameter is the learning rate. If it is too small, training is slow. If it is too large, training can bounce around or fail to converge.

new_weight = old_weight - learning_rate * gradient

This process explains why training loops repeat parameter updates.

4. Epoch, Batch, and Iteration

Deep learning training often uses these terms:

  • Epoch: one full pass through the training set
  • Batch: a small group of samples used for one update step
  • Iteration: one parameter update

With 1000 samples, batch size 100, and exactly one parameter update per batch, an epoch contains 10 iterations. Gradient accumulation or skipped updates requires recording batches and parameter updates separately.

Traditional machine learning libraries may not expose these terms directly, but the basic idea is similar: the model uses training data to adjust parameters.

5. Why Overfitting Happens

Overfitting occurs when a model fits details or noise specific to its training sample at the expense of performance on new samples from the target distribution. A deployment distribution shift can also create a performance gap and needs a separate check.

Common causes include:

  • The model is complex enough to memorize noise and details in the training set
  • The training data is too small to represent the real problem
  • Also check data leakage separately: unavailable information entering training or evaluation breaks the validation boundary
  • The model trains for too long without validation monitoring

The danger is that training metrics can look excellent while real-world performance is poor.

6. Training, Validation, and Test Data

For reliable evaluation, data is often split into three parts:

  • Training set: used to fit parameters
  • Validation set: used to tune settings, select models, and watch for overfitting
  • Test set: used at the end to estimate final generalization

A fixed teaching configuration can use a training/test split. If models or settings are selected, use a validation split or cross-validation inside the training partition and keep the final test set out of those decisions.

7. Common Classification Metrics

Classification should not be judged by accuracy alone. These metrics often appear together:

  • Accuracy: the proportion of correct predictions
  • Precision: among predicted positives, how many are truly positive
  • Recall: among all actually positive samples, the proportion predicted positive
  • F1-score: a combined measure of precision and recall

For medical screening, missing a real positive case may be costly, so recall may matter more. For automatic account blocking, falsely blocking normal users may be costly, so precision may matter more.

8. Reading a Confusion Matrix

A confusion matrix compares predicted labels with true labels:

                  predicted negative  predicted positive
true negative              TN                  FP
true positive              FN                  TP
  • TP: a positive sample predicted correctly
  • TN: a negative sample predicted correctly
  • FP: a negative sample incorrectly predicted as positive
  • FN: a positive sample incorrectly predicted as negative

The advantage of a confusion matrix is that it shows not only how many mistakes happened, but also which direction those mistakes went.

A worked example: positive does not necessarily mean label 1

The companion Python exercise produced [[41,1],[1,71]] in this rerun, ordered as [0=malignant, 1=benign]. If the teaching question concerns finding class 0, the top-left 41 is TP, not TN. Do not apply the template above without first identifying the classes.

Taking class 0 as positive gives TP=41, FN=1, FP=1, TN=71. Precision and recall are both 41/42=0.976190. Calling recall_score(y_true, y_pred) without specifying a positive label instead evaluates class 1 and returns 71/72=0.986111. Both calculations are valid but answer different questions. The row and column convention is documented in scikit-learn confusion_matrix.

After running the reproduction package, reconstruct the calculation from the complete predictions rather than typing in the matrix you expect:

import pandas as pd
from sklearn.metrics import confusion_matrix, recall_score

rows = pd.read_csv("results/predictions.csv")
y_true = rows["true_label"]
y_pred = rows["predicted_label"]
print(confusion_matrix(y_true, y_pred, labels=[1, 0]))
# [[71  1]
#  [ 1 41]]
print(recall_score(y_true, y_pred, pos_label=0))
# 0.9761904761904762

The majority baseline on this same split has matrix [[0,42],[0,72]] and 63.16% accuracy despite zero recall for class 0. Report accuracy, class meaning and the baseline together. With only 114 test rows, one changed prediction moves accuracy by about 0.877 percentage points; that is not a confidence interval or a bound on real error. This recalculation audits the teaching result, not clinical validity or future performance.

9. Evaluation Checklist

When evaluating a model, check these questions:

  • Was the test set isolated from training?
  • Are the classes heavily imbalanced?
  • Did you look beyond accuracy?
  • Was the model compared with a simple baseline?
  • Did you inspect some wrong predictions manually?
  • Is the gap between training performance and test performance too large?

Evaluation should identify the conditions under which the model works and those under which it is likely to fail.

10. Evaluation Evidence Matrix

A reliable training report connects metrics to decisions. The table below shows what to record before deciding that a model is ready for a demo, article, or deployment experiment.

Evidence item What to record Decision it supports Warning sign
Split integrity Random seed, stratification, grouping rule, and test isolation Whether the test score estimates new-data behavior Repeatedly tuning on the test set until the score improves
Metric choice Accuracy, precision, recall, F1, ROC-AUC, or task-specific cost Which error type matters most Using accuracy on a heavily imbalanced dataset without context
Baseline comparison Majority-class baseline, simple linear model, or previous version Whether the trained model adds value A complex model beats no documented baseline
Error review Confusion matrix and representative wrong predictions Whether failures are random, systematic, or unacceptable High average score hides rare but costly mistakes

11. What a Trustworthy Training Record Includes

A useful training record should include at least these details:

  • How training, validation, and test data were split
  • The model, important parameters, and random seed
  • Training metrics and test metrics, not just one final score
  • Error analysis, especially for the most costly error types
  • Comparison against a simple baseline model

These notes let you trace the result when you return to the experiment later.

Use the validation set enough and it becomes a second training set

Repeated tuning against validation scores uses validation-set information to select the model. A separate test set is needed to assess performance on unseen data.

Hyperparameters can be fixed in advance or selected using validation results. Once a validation score informs changes to learning rate, depth, regularisation, or features, that information participates in model selection. Repeated searches can adapt the choice to chance features of the validation sample.

The validation score still describes performance under the current protocol, but repeated selection prevents it from serving as an independent assessment of new-data performance. Preserve the search history and evaluate the selection procedure with an isolated test set or outer validation.

The standard remedy is a third split you never look at:

training     learns parameters      -- used directly by the model
validation   selects hyperparams    -- you inspect it repeatedly, so it gets fitted
test         final report           -- sealed throughout, opened once

If a test score informs another change, those test records have entered development. A new independent assessment needs data not previously used for fitting or selection; randomly repartitioning already-exposed data does not restore independence. Alternatively, retain the current data and report the development process explicitly.

With limited data, cross-validation can replace a fixed validation partition. Split the training portion according to the task, evaluate the folds, and refit preprocessing within each fold. Ordinary k-fold uses each record for training and validation; grouped or temporal schemes follow their own rules. Cross-validation does not automatically remove selection bias or distribution mismatch.

from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X_train, y_train, cv=5)
print(scores.mean(), scores.std())   # the standard deviation matters equally

Read the standard deviation alongside the mean. The two sets of five-fold scores below have identical means of 0.896:

A: 0.91  0.89  0.90  0.90  0.88     mean 0.896   std 0.010
B: 0.98  0.76  0.97  0.78  0.99     mean 0.896   std 0.103

The five scores for A are more concentrated, while B varies more across folds. These are differences among subsets in one fold assignment, not evidence that a new split’s overall mean ranges from 0.76 to 0.99. Fold standard deviation is not a standard error or confidence interval for generalisation because the training folds overlap.

Report the mean, fold scores, and spread, then inspect class support, entity groups, time ranges, preprocessing boundaries, and errors. Stratification can address class balance; repeated entities require group boundaries; future forecasting requires temporal validation. These are different assumptions and do not share one universal splitting fix.

12. What to Read Next

The previous article is Machine Learning Workflow. After training and evaluation are clear, continue with Neural Network Basics to connect parameters with multi-layer function composition.

Leave a Reply

Scroll down