Article sections
What does training actually learn?Choosing a loss functionWhat do SGD, Adam, and AdamW change?Learning rate and schedulingBatch size and mixed precisionHow do you distinguish overfitting from underfitting?Fine-tuning and freezing layersTraining logs and final model selectionField scenarioMaking the training step and experiment budget explicitFrequently asked questionsReferencesWhat does training actually learn?
Deep learning training is the process of finding parameters that reduce the mismatch between a model's predictions and its target labels. The process in which an image enters the model and an output prediction is produced is called forward propagation, while transmitting the error signal back to the parameters is called backpropagation. The optimizer uses these gradients to update the weights. This chain is not merely a mathematical operation: image preprocessing, label definitions, and the way samples are selected also change the behavior the model learns.
For example, if scratches in training images are mostly visible under a single lighting setup, a classifier that detects scratches on metal surfaces may learn the reflections produced by that lighting rather than the scratches themselves. A decrease in training loss is not evidence that the model has learned the right underlying cause. Validation data and diversity in production batches and image acquisition conditions are therefore integral parts of training.
Choosing a loss function
The loss determines how the model is penalized. Binary cross-entropy is common in binary classification, while cross-entropy is common in multiclass tasks. In segmentation, Dice- and IoU-based losses may differ in their sensitivity to class imbalance and boundary quality; in detection models, classification and bounding-box regression are separate components. Lower loss values can be compared directly only when the loss definition and data are the same.
Focal loss or class weights may be considered for rare defects, but these techniques do not eliminate labeling errors. Very high weights for defects can also increase false alarms. When choosing a loss, consider the decision cost per product, the importance of mask boundaries, and the pixel area of the defect together.
What do SGD, Adam, and AdamW change?
SGD follows the gradient-based update direction; momentum can retain the influence of previous updates. Adam adapts updates for each parameter using the first and second moments of the gradients. AdamW decouples weight decay from the adaptive update. None is automatically superior on every dataset. Fast convergence, good generalization, and stable results are distinct goals.
An optimizer comparison should match training time, initial learning rate, weight decay, random initialization, and training budget. A method that performs better in one run may not retain that advantage across different initializations. The decision should be based on validation metrics and cost, not just the lowest loss.
Learning rate and scheduling
The learning rate determines the size of each update. A rate that is too high can cause the loss to oscillate or diverge; a rate that is too low can make training unnecessarily long and limit progress. Warmup, cosine decay, and step decay are common scheduling methods. The choice of schedule should be guided by the behavior of the training curve and the total step budget, not simply by whether it is considered modern.
Rather than looking only at the final point, curve analysis should examine stability in the initial epochs, the response to learning rate changes, and divergence between validation and training loss. When validation metrics are noisy, a difference in a single epoch should not be treated as a success.
Batch size and mixed precision
As batch size increases, memory requirements rise and gradient estimates generally become less noisy; however, this does not always improve generalization. Small batches may require more updates. If GPU memory is limited, gradient accumulation can increase the effective batch size. Mixed precision can offer speed and memory advantages on some hardware, but numerical overflow must be monitored.
Downscaling an entire high-resolution industrial image can erase small defects. In such cases, patch-based training, a multiscale approach, or the use of ROIs may be considered. Each changes how per-image outputs are interpreted and the cost of combining them.
How do you distinguish overfitting from underfitting?
If training performance improves while validation performance declines, overfitting is a possibility. If both are poor, the model may lack capacity; however, incorrect labels, an unsuitable loss, or faulty data preprocessing can produce a similar pattern. The two curves are therefore a starting point for diagnosis, not a definitive conclusion on their own.
Weight decay, early stopping, data augmentation, and a smaller architecture can improve generalization. But if we change them all at once, we cannot tell which intervention worked. A sounder approach is to check data integrity first, then conduct controlled experiments that change one variable at a time.
Fine-tuning and freezing layers
A pretrained backbone is a valuable starting point when labeled data is scarce. A common strategy is to train only the classification head initially, then unfreeze selected layers at a low learning rate. If the source and target data differ substantially, more extensive adaptation may be necessary. However, when data is limited and noisy, unfreezing the entire network can increase the risk of memorization.
The behavior of frozen BatchNorm layers, data normalization, and input resolution must not be overlooked. The adequacy of pretrained features should be verified through testing, especially for highly reflective materials.
Training logs and final model selection
Saving only the weights file from a successful run is not enough. The data version, training/validation split, code and configuration versions, seed, loss components, optimizer, and hardware details should be recorded. The criterion used to select the best checkpoint should be stated. Repeatedly selecting checkpoints using the test set contaminates the evaluation.
The decision on the final candidate should consider a one-time evaluation on the held-out test set, different production conditions, and resource consumption together. Training logs and production results measure different things; both are necessary.
Practical field scenario: training for metal surface defect detection
In a scenario where data is collected from three different production batches, begin with a model that trains only the final classification layer. If recall drops on a new batch despite decreasing training loss, investigate data representativeness and the suitability of pretraining. In the next experiment, use crops that preserve small defects and recalculate the speed and memory budgets. This example shows that method selection does not depend on the architecture's name alone.
How do you develop a training strategy for field conditions?
First, fix all transformations and image formats in the data pipeline. If a sensor's 12-bit raw image is scaled to 8-bit, document the threshold and gamma transformation used; otherwise, training and the live system may produce different pixel statistics. Use a simple baseline, a reasonable learning rate, and a single validation protocol in the first training run. In the second step, use the learning curves to choose just one intervention to test: data augmentation, weight decay, a more suitable resolution, or unfreezing layers.
The compute budget is also a business constraint. Even if a larger batch shortens training time, it does not directly determine memory consumption during inference; training and production resources should be measured separately. Model weights must be saved, inference preprocessing validated, and performance retested after optimization.
When should training stop?
Early stopping differs from training for a fixed number of epochs: training ends if a preselected validation metric fails to improve for a specified period. However, when validation results are very noisy, the patience setting and the minimum meaningful improvement threshold must be chosen carefully. In a project where checkpoints are selected by recall, later deploying only the model with the lowest loss constitutes a change in methodology.
If performance remains high on training data but low on a new production batch after repeated experiments, investigate the data distribution and physical imaging conditions rather than training longer. If the necessary samples are unavailable, report the data gap instead of making a performance claim.
A brief example for a training report
A project report stating, "The backbone was pretrained, the head was trained for the first five epochs, and the last two blocks were unfrozen in subsequent epochs; training used AdamW," is a start, but it is not enough. The learning rate, weight decay, batch size, seed, training time, input size, defect classes, number of repeated runs, checkpoint selection criterion, and independence of the actual test must also be reported. After a significant change, explicitly state whether the same data split was used as for earlier results and whether the test protocol changed.
Points to check in the field
- Data source: Clearly define the product, batch, camera, shift, and sampling method.
- Decision unit: Do not conflate measurements at the image, defect, product, and production-line levels.
- Success criterion: State the metric target together with latency, throughput, cost, and tolerance for critical errors.
- Alternatives: Assess whether simpler methods and improvements to the physical setup can meet the same need.
- Validation: Use a test protocol that is independent of the training data and representative of production conditions.
- Change log: When the model, threshold, optical settings, or label definitions change, archive the rationale for the decision and its outcomes.
Making the training step and experiment budget explicit
Recording only the optimiser name is insufficient to reproduce a training run. Suppose there is one image for each of 2,400 independent parts and the batch size is 24. With equally sized batches, one epoch contains 100 optimiser updates, so 20 epochs contain 2,000 updates. Doubling the batch size changes the update budget even if the epoch count stays fixed. This illustrative calculation assumes no gradient accumulation.
The forward pass produces predictions, loss.backward() computes gradients and optimizer.step() updates parameters. A standard loop calls optimizer.zero_grad() first when accumulation is not intended. Validation switches layer behaviour with model.eval() and separately disables gradient computation; these operations are not interchangeable. Differences such as training-only augmentation must also be recorded when comparing training loss with validation results.
Start with a trained head and fixed data split and input size. In the next run, unfreeze the final blocks; in another, change the learning rate. Choose checkpoints using a predefined validation criterion rather than the final test. Record the data version, seed, update count, training time, hardware and failed runs. This makes it possible to check whether lower loss actually improves decisions on new parts.
Frequently asked questions
Why do training and validation loss diverge?
The model may fit training samples better without generalizing to new samples; data shift and label mismatches should also be investigated.
Is longer training always better?
No. More epochs without early stopping and independent validation can increase overfitting.
References and further reading
The primary sources below explain the methods and evaluation protocols. Numerical scenarios in this article are educational examples, not measured results from a facility or model.