Article sections
What is image classification, and what is it used for?Binary, multiclass, and multilabel classificationHow do you select the image region for classification?Where do CNNs and ViTs differ?What is transfer learning?What are the risks of fine-tuning?When does patch-based classification offer an advantage?Are classification scores probabilities?Why is accuracy misleading for rare defects?Why is claiming that Grad-CAM found a defect not enough?Dataset shift and unexpected errors in productionWhen is image classification unsuitable?Numerical example: the cost of a product sorting decisionSuggested experimental setup for model comparisonPredeployment checklistDesigning classification around error costsLabel ambiguity affects the model's performance ceilingImage dimensions, patch size, and computational budgetDecisions about the classification head and loss functionWhy are confidence intervals and repeated experiments necessary?Combining active learning with human reviewFrequently asked questionsVisual sourcesBinary, multiclass, and multilabel classification; transfer learning, decision thresholds, patch-based approaches, and systematic error analysis. This guide examines the assumptions behind these methods, the conditions in which they can be used, the reasons they fail, and the decision points encountered in production.
What is image classification, and what is it used for?
Short answer: Image classification is a learning problem that assigns one or more class labels to an image or to a specific region extracted from it. In production inspection, it can support decisions such as 'conforming/defective,' 'correct/incorrect product,' 'part type,' or 'process completed/not completed.' However, the output usually does not indicate a defect's location or size. If the aim is to know why a product was rejected or which area needs repair, additional visual outputs may need to be included in the task definition.
Classification seems simple because it produces a single probability or score. In reality, which unit of the image the system classifies matters as much as what it looks at. Will we evaluate the entire photograph, only the part, or local patches measuring 256 × 256 pixels? If a defect occupies only one thousandth of the photograph, whole-image classification may become difficult. Conversely, using only a local patch loses context in cases such as an incorrectly assembled product.
Binary, multiclass, and multilabel classification
Binary classification usually involves two opposing decisions, such as conforming and defective. In multiclass classification, a single image is assigned to only one of several options: product type A, B, or C. In multilabel classification, the same image can contain both a scratch and a stain, and both labels can be correct simultaneously. This distinction changes the entire system, from output activation to annotation guidelines.
Independent class scores, such as sigmoid outputs, are common for binary and multilabel tasks, while softmax is common for mutually exclusive multiclass tasks. However, the technical choice cannot be explained solely by the name of the final layer: decision thresholds, a cost matrix, and consistent labeling are also required. Training three defect classes with mutually exclusive labels while expecting two different defects to occur on the same part is a structural design error.
For example, if porosity and cracks can occur simultaneously in a weld seam, a multilabel output makes sense. But if the only decision is 'is this product acceptable?', a single quality score may also be operationally sufficient. An unnecessarily detailed label hierarchy increases data collection and annotation costs. The engineering action each label will trigger should be defined at the outset.

How do you select the image region for classification?
Images captured in production sometimes contain more conveyor, protective glass, cabling, or background than the object itself. A model may happen to predict the correct label by relying on these regions. Cropping the part from a fixed region, masking it, or acquiring it with a suitable ROI simplifies the learning problem. However, an overly tight crop may leave the defect at the boundary or remove context that indicates the part's orientation.
If the ROI is fixed, the part's mechanical positioning and camera tolerances must be known. A shift of a few millimeters in the camera mounting can cause the production crop to differ from the training crop. The approach of 'train on the data first, then position the camera' leads to costly rework in many production problems.
Where do CNNs and ViTs differ?
CNN families such as ResNet extract convolutional features hierarchically. EfficientNet is known for a design approach that considers model scaling jointly in terms of depth, width, and input resolution. ViT converts images into patch tokens and establishes relationships through attention. Rather than judging models by name alone, compare them in terms of pretraining, image resolution, parameter count, on-device latency, and the physical scale of the defect.
Some defects are particularly difficult to classify: scratches with very little color change, dents visible only at certain lighting angles, and surface marks resembling normal production texture. A larger backbone may not be the only solution for these tasks. More stable lighting, suitable optics, or rotating the part to capture another angle may deliver greater improvements than changing the model.
What is transfer learning?
Transfer learning means using a representation pretrained on a large dataset for a new task. A new classification head is added to the pretrained backbone. Initially, only this head may be trained; if sufficient data is available, the backbone's final blocks or the entire backbone can be fine-tuned in a controlled way. This approach can work with limited labeled data, but it does not deliver the same results in every target domain.
Pretraining on images of everyday objects should not be expected to work well directly in domains such as microscopy or narrowband infrared sensor data. Transformations of color channels, resolution, and image statistics must be documented explicitly. If several cameras are used in production, differences in calibration and lighting behavior between cameras also carry through to the model.
What are the risks of fine-tuning?
Updating all layers at a high learning rate on a small dataset can unnecessarily damage general representations acquired during pretraining. Conversely, training only the final layer may not be enough to distinguish new surface textures. Gradual fine-tuning offers a controlled experimental path between these two extremes. Random seed, training duration, input resolution, and data augmentation should be held fixed across experiments.
Repeated images are another important risk. If different frames of the same part are randomly distributed between training and validation sets, the model can appear better by learning part identity. Grouping should therefore be based on the part, production batch, or capture session. The goal is to measure behavior under previously unseen real production conditions, not merely on a previously unseen image.
When does patch-based classification offer an advantage?
Dividing a large image into small patches can make a local defect more visible. For example, a single photograph of a metal sheet may be 4096 × 4096 pixels, while the defect is 20 × 5 pixels. If the entire image is reduced to 224 × 224, the defect almost disappears. Working with 512 × 512 patches, however, can preserve the defect's relative size. The trade-off is that a single product requires more model calls and a decision about how to combine them.
The patch overlap ratio also matters. With no overlap, a scratch may be split in two at a patch boundary. With very high overlap, the same defect is counted repeatedly and data processing costs rise. The final decision can use a maximum anomaly score, a mean score, or patch-based alarm rules; however, an oversensitive maximum rule can increase the false alarm rate. This behavior must be measured using normal production data.
Are classification scores probabilities?
A model output of 0.97 does not mean that the actual probability of a defect is 97%. Softmax or sigmoid outputs should generally be treated as scores; calibration must be examined before interpreting them as probabilities. Overconfident models can produce incorrect predictions with high confidence, particularly under unseen material or lighting conditions.
The decision threshold is selected according to operational requirements. If missing a defective product is costly, the threshold can be set for greater sensitivity. This may increase the rejection of conforming products. Although the decision itself appears mathematically simple, the final choice depends on production speed, rework capacity, and the potential impact of a missed defect.
Why is accuracy misleading for rare defects?
Suppose 5 out of every 1000 products on a line are defective. A classifier that labels every product 'conforming' achieves 99.5% accuracy, yet detects no defects at all. This example shows why accuracy alone should not be used under class imbalance. Recall, precision, false-positive rate, and the number of missed defects should be reported together. The question of how many of every 100 parts flagged by an alarm are actually defective is particularly important for operator workload.
For example, if defect prevalence is 1%, recall is 95%, and the false alarm rate on conforming parts is 2%, approximately 95 true alarms and 198 false alarms occur among 10,000 products. Of the 293 total alarms, only about 32% represent genuine defects. This does not necessarily mean that the model is poor; a low base rate strongly affects precision. This arithmetic must be considered when setting production acceptance criteria.
Vary the defect rate and false alarm rate in a hypothetical shift of 10,000 parts. This calculation is not model training.
Probability that an alarm represents a genuine defect: —
Total alarms: —
Why is claiming that Grad-CAM found a defect not enough?
Grad-CAM can combine intermediate activations and gradients to visualize regions associated with a decision. However, high activation is not evidence of a genuine defect. The model may be predicting the class from a barcode, logo, background, or edge reflection. Overlap between the map and a human annotation is a useful clue, but does not by itself replace reliability testing.
It is necessary to measure how the model's decision changes when the defective region is occluded, whether the score remains stable when the same defect is photographed against different backgrounds, and whether a normal reflection triggers an alarm. An explanatory visual should generate an engineering hypothesis, not serve as marketing decoration.
Dataset shift and unexpected errors in production
The image distribution can change over time. A new material supplier, a change in the ground surface finish, dirty protective glass, a different line operator, or changing lighting are normal occurrences in actual production. These changes are not product defects, but the model may confuse them with defects. The validation set must therefore represent different batches, shifts, and time periods.
When results are unexpected, the first investigation should focus on the data flow rather than the model weights. Is the camera exposure different? Has ROI alignment shifted? Has the normalization stage changed? Could the wrong product variant be under inspection? Was the recorded image compressed before reaching the model input? Simple implementation errors are often cheaper to fix than training a new model.

When is image classification unsuitable?
If defect coordinates are required, a class label alone is insufficient. Detection or segmentation may be necessary if a repair robot needs to locate a welding point, scratch length must be measured, or two defects must be counted separately. Classification can nevertheless be valuable as an initial screening stage; for example, a fast classifier can direct suspect products to detailed inspection.
If defect types cannot be predefined and only images of normal products are available, anomaly detection may be a more natural starting point. However, an unsupervised anomaly method can also mistake different lighting for a defect. The questions 'are labels available, is location required, and are all defect types known?' help determine the problem category.
Numerical example: the cost of a product sorting decision
Suppose a line processes 25,000 products per shift and the actual defect prevalence is 0.8%. The number of genuinely defective products is approximately 200. If the model detects 96% of these, there are 192 true alarms and eight missed defects. With a 0.6% false alarm rate on conforming products, approximately 149 conforming products are also diverted. The operator must inspect 341 products in total; 56% of these are genuinely defective.
The purpose of this calculation is not to recommend a single threshold. On the same line, sensitivity can be increased if false rejection costs are low. If false rejections cause substantial downtime, a more selective system may be necessary. Costs should be calculated per product, per shift, and by defect severity. When model selection is not linked to business outcomes, the reported success percentage does not describe actual productivity.
Suggested experimental setup for model comparison
A traditional image processing baseline, a lightweight CNN, a larger pretrained CNN, and a ViT can be compared using the same group-based training/validation/test split. Input resolution and defect types are held as constant as possible. Image-level and product-level metrics are reported separately during testing; if multiple frames belong to one product, the aggregation rule for the product decision is defined in advance.
| Aspect examined | Minimum question | Validation method |
|---|---|---|
| Representation | Is the defect actually visible? | Pixel scale and example inspection |
| Data | Do training and test sets contain related examples? | Group and duplicate checks |
| Model | Does it outperform the baseline under the same conditions? | Fixed test and confidence interval |
| Decision | Does the threshold match the error costs? | Precision–recall and error table |
| Deployment | Is the latency requirement met? | End-to-end testing on the edge device |
Predeployment checklist
Verify that the classification task is correctly defined as single-label, multiclass, or multilabel; that the image region and cropping rule are fixed; that defect dimensions are preserved at the input resolution; that group-based testing is prepared; and that different shift and batch conditions have been evaluated. Which product the positive class refers to, how the alarm decision is made, and what the operator should do with uncertain results must be documented.
Also retain the data version used to train the model and the threshold used at deployment. Archiving model weights alone is insufficient; preprocessing, the label dictionary, calibration, and downstream business rules are also parts of the system. Being able to reproduce the same decision for the same image genuinely simplifies maintenance.
Designing classification around error costs
On a production line, a false negative means accepting a defective part as conforming, while a false positive means unnecessarily rejecting a conforming part. These two errors often do not have the same cost. Missing a structural crack may pose a safety risk, while rejecting a conforming product may merely incur additional inspection costs. Conversely, for very expensive or nonrecyclable product groups, false rejection can cause serious economic loss. The target should therefore be a cost-sensitive decision policy, not just average accuracy.
A simple cost matrix can be constructed: a missed critical crack, a missed cosmetic stain, a false rejection, and an operator review each carry different costs. The model score threshold is evaluated on the validation set together with these costs. However, if defect prevalence changes in actual production, the expected number of alarms at a given threshold also changes. Any threshold change must be reflected in a new acceptance test and configuration version.
A single 'defective' class can hide differences in defect severity. For example, assigning the same error cost to a slight color variation and a critical material crack is technically inappropriate. In such cases, multilabel classification, a defect severity score, or referral to expert review may be considered. This requires labels to be defined consistently within the organization.
Label ambiguity affects the model's performance ceiling
Even experienced quality specialists may disagree on whether some surface marks count as defects. Creating a single hard class label in this situation asks the model for a definite answer to a decision that is inherently uncertain. The disagreement may originate primarily in product tolerances, the measurement procedure, or a customer standard. A model cannot resolve an ambiguous quality policy on its own.
An annotation standard should be supported by example images. Images of borderline defects and the reasons for decisions can be retained. Measuring inter-annotator consistency can reveal which defect types generate disagreement. Keeping the label dictionary stable over time is as important as choosing correctly between multilabel and multiclass structures.
Reducing training loss to nearly zero on a dataset with noisy labels does not mean success. The network may memorize incorrect labels. Excluding difficult examples entirely is also dangerous: genuinely critical but rare defects may be lost in the pursuit of 'clean data.' Data cleaning decisions should be made jointly with the quality team.
Image dimensions, patch size, and computational budget
If the camera produces 20 MP images, direct full-resolution classification can be expensive in terms of GPU memory and latency. Downsizing the image is the easiest option, but it also shrinks fine defects. A patch-based approach preserves physical detail while requiring more inference calls. Patch size, overlap ratio, and the regions to inspect must therefore be planned together.
For example, dividing a 4000 × 3000 image into 512 × 512 patches requires approximately 8 × 6 = 48 patches without overlap. If inference takes 4 ms per patch, sequential model calls alone take approximately 192 ms, excluding preprocessing and communication. Batch inference can reduce this time, but may increase memory use and the time spent waiting to form a batch. A paper describing a '4 ms model' does not mean a product is inspected in 4 ms.
Combining patch results at the product level creates another problem. Looking only at the maximum score can increase false rejections because of a single noisy patch. Looking at the mean can hide one genuine fine defect among the other normal patches. Options such as regional priority, top-k scores, or a sequential second inspection should be tested for production use.
Decisions about the classification head and loss function
Binary cross-entropy is a common starting point for binary tasks. Categorical cross-entropy can be used for multiclass tasks, and independent class losses for multilabel tasks. However, the loss function must match label semantics. If defects can coexist on the same product, using softmax to make a single mutually exclusive decision defines the model's mathematical objective incorrectly.
Options such as weighted loss or focal loss can increase the influence of a rare class. However, raising the weight too much can cause frequent false rejections of conforming parts. A class weight during model training is not the same as a production decision threshold; they should be optimized separately. Differences between the actual defect base rate and the sampling rate during training can also affect output score calibration.
Examining confusion between classes is more informative than reporting overall accuracy alone. Are scratches confused with normal machining marks, or is breakage confused with stains? The physical causes of these confusions may differ. The confusion matrix, example visuals, and optical conditions should be assessed together.
Why are confidence intervals and repeated experiments necessary?
In a small test set, one or two examples can change the result substantially. For example, detecting 19 of 20 critical defects means 95% recall; one additional miss reduces this to 90%. A few percentage points between two models may not indicate genuine superiority. The number of independent physical events in the test set and the uncertainty must be considered.
Methods such as bootstrapping can help estimate uncertainty, but the sampling unit must be chosen correctly. In a system where the same part produces 30 frames, treating individual frames as independent artificially narrows the confidence interval. Grouped resampling at the product, batch, or production-session level may be more meaningful.
The results report should describe the seed, data split, training epochs, best-checkpoint selection, and threshold tuning. The statement 'Model B is 0.8% better' is insufficient for a production decision without uncertainty and error costs.
Combining active learning with human review
Not every classification system has to make automatic decisions for every image. Low-confidence examples can be sent to the quality team, and expert decisions can be added to a feedback dataset. Such a workflow can improve the representation of rare and ambiguous defects over time. However, human decisions can also be wrong, and measuring expert consistency remains necessary.
Human review capacity is limited. Generating 10,000 alarms a day and sending 10% to an operator may not be practical. The system's human-review threshold should be determined from the review time per example per operator and shift capacity. For example, if reviewing one example takes an average of 15 seconds, 1000 examples require approximately 4.2 hours of pure review time.
Reviewed examples can help improve the model, but adding those same examples back into the test set compromises independent performance measurement. As production feedback enters the training pool, a separate monitoring test set refreshed over time and fixed acceptance tests should be maintained.
Advanced engineering details to consider in production
Part-level versus image-level decisions
Suppose four cameras inspect a product simultaneously. Classifying each camera's image separately is straightforward, but production requires a single accept-or-reject decision for one part. If the part is rejected whenever any image shows a critical defect, OR logic can increase the false alarm rate. Using the mean score, however, may allow a highly critical defect to be suppressed by the other three normal images. How image scores are combined must therefore be designed together with the product standard. The decision must be validated not only at model level, but also at the part-identity and image-acquisition-system levels.
Multilabel and hierarchical labels
A part can have both a scratch and discoloration. In that case, single-label classification discards some defect information; a multilabel setup is more appropriate. However, some labels are mutually exclusive, while others may be related. For example, the parent class 'surface defect' may include 'scratch,' 'dent,' and 'contamination.' Model outputs do not automatically comply with this hierarchy. The dataset's annotation guidelines should explain which combinations are meaningful and how ambiguous examples should be handled. The first step in a good classification system is defining the target correctly.
Thresholds, costs, and decision policy
A classifier score of 0.75 cannot necessarily be assumed to mean a 75% probability. Scores may be uncalibrated, and the same score may have a different meaning when class prevalence changes. A three-region decision policy based on two thresholds can sometimes be safer: automatically accept high-confidence conforming products, automatically reject high-confidence defective products, and send examples in between for human inspection. However, human inspection capacity is also limited. On a line processing ten thousand products a day, a 2% review rate means two hundred manual inspections. The model threshold, quality target, and operator workload must be determined together.
Cropping and loss of context
Cropping small parts out of large images and classifying them individually can make sense. However, if cropping conceals the product's position or its relationship to surrounding components, the model may reach the wrong conclusion. A screw looking sound on its own does not mean it is installed in the right place. Likewise, if darkness in a region results from the normal lighting angle, it is difficult to interpret without the surrounding surface. When selecting crop size, consider the defect's minimum physical size, the extent of context required, and input resolution together. The cropping logic used in training must match the logic used in production.
Application scenario: one product decision from four cameras
Suppose images are collected from the top, bottom, and two side surfaces of a part. Each camera's prediction is associated with the product identity. If one of the parts is mismatched, the product decision may be wrong even when the classifier works with 100% accuracy. Evaluation should therefore cover individual parts, lines, and shifts, not just images. Choosing a lower threshold for a critical surface does not mean that the same threshold is appropriate for other surfaces.
Field test checklist
- Is it documented which tests were kept independent by product, shift, and capture conditions?
- Have failures correctable by the algorithm alone been distinguished from those requiring optical or process changes?
- Has it been verified that the model score does not replace physical acceptance criteria?
- Are input resolution, model version, threshold, and operating hardware held fixed in the experiment records?
- Are illustrative visuals clearly distinguished from actual measured model results?
- Are false rejections, missed defects, latency, and reinspection workload reported separately?
Frequently asked questions
What is the difference between classification and object detection?
Classification assigns a label to an image; object detection also produces bounding-box coordinates for one or more objects within the image. Detection may be more appropriate if the defect's location is needed.
Should you choose ResNet or EfficientNet?
No single model family is superior for every task. They should be compared in the same test, considering pretraining, input size, target device, data coverage, and error costs.
Is classification possible with few defective examples?
Yes, transfer learning or a patch-based approach may help. However, narrow data coverage increases the risk of poor generalization in actual production. If normal images are abundant and defect types are uncertain, anomaly detection can also be tried.
Is the result reliable if the confidence score is 99%?
No. Calibration is required to interpret the score as a probability; overconfident errors can occur under unseen conditions.
When should patch classification be used?
It may be useful when a defect occupies a small portion of a large image. However, patch count, overlap, product-level alarm aggregation, and speed costs must be designed together.
References and visual provenance
Technical references and original publications are listed below. Photographs used in the visual examples come from real CC0/public-domain examples; transformations made for comparison are explained. The diagrams are original designs. Illustrative examples are not presented as trained-model performance.
Visual sources and illustration note
The photographic examples come from the scikit-image sample data collection. Added boxes, masks, synthetic defects, and heatmaps are illustrations explaining the concepts; they are not outputs from a trained model or validated performance results. The technical diagrams are original drawings included in the package.