Article sections
1. When does natural class imbalance become a problem?2. The difference between rare defects and difficult defects3. What is a hard negative?4. Why should recall, precision, and false alarms be evaluated together?5. Interactive example: How does defect prevalence affect alert quality?6. How should rare defects be prioritized during data collection?7. Are oversampling and undersampling always a solution?8. How do you establish a hard negative mining workflow?9. The PR curve, ROC curve, and decision threshold10. The cost of false rejection and the cost of missing defects11. Why must critical defect classes be examined separately?12. How do you proceed if a rare defect has never been observed?13. Example scenario: 10 defects in 10,000 parts14. How should a sound rare defect evaluation be reported?15. Threshold optimization is not just a model problem16. How can data distribution shift be confused with the rare defect problem?17. Statistical uncertainty in rare defects18. How do you prepare a sound experimental comparison?19. An operational loop for data collection and human inspection20. Setting an operational target between defect detection and false alarmsFrequently asked questionsOn production lines, defective parts are generally far less common than good parts. Although encouraging at first glance, this can become a serious data problem for a team developing an image processing model. If there are only a few critical cracks among tens of thousands of defect-free examples, the model gravitates toward the majority class during training; during evaluation, even a small false alarm rate can mean rejecting many good parts every day.
Class imbalance means that classes occur at different frequencies during training. Managing rare defects, however, is broader than this: the actual production defect rate, different defect subtypes, the cost of missed defects, the burden of false rejection, and hard negatives that 'look defective but are acceptable' must all be considered together. This article explains data collection, sampling, hard negative mining, threshold selection, and testing strategies from an industrial decision-making perspective. The example images and numbers are for educational purposes.
1. When does natural class imbalance become a problem?
Imbalanced data is not inherently a data error. On a healthy production line, good products are expected to form the majority. Problems arise when the model cannot learn important but rare patterns, when the evaluation provides insufficient evidence for these patterns, or when false rejection costs are overlooked. Unless the difference between the training distribution and the field distribution is deliberately managed, the model's score does not represent the production decision.
For example, if only 100 of 100,000 parts are defective, the defect rate is 0.1 percent. A model that calls every part good achieves 99.9 percent accuracy but detects not a single defect. This example shows how misleading accuracy can be for rare events. It does not mean that 'accuracy is entirely useless'; it only shows that accuracy should not be used as the sole acceptance criterion.
Defect prevalence can vary by product family, season, maintenance period, and supplier. Calculating a single overall rate can hide, for example, a critical defect concentrated on a particular machine. Alongside overall prevalence, examine distributions by product, line, shift, and batch during data analysis. However, apparently high rates in very small groups may have substantial statistical uncertainty.
2. The difference between rare defects and difficult defects
A defect is not necessarily difficult because it is rare. An obvious missing hole that occurs only a few times a year can be easy to distinguish with appropriate image acquisition. In contrast, a low-contrast surface variation seen every day can be difficult because the boundary between defective and good is unclear. A data collection plan should treat these two axes separately: frequency of occurrence and visual distinguishability.
Diversity is another dimension of rare defects. Ten different crack images do not represent the full diversity of the defect's appearance if they are merely ten near-duplicates of a single physical part. Model behavior can differ as the crack's orientation, length, surface region, material texture, and lighting angle change. Rather than setting a target of '100 images of the critical defect,' asking 'how many independent examples and how many different conditions?' is therefore more meaningful.
Visually difficult defects sometimes require better lighting rather than more labeled data. If a fine crack on shiny metal is entirely invisible without changing the camera angle, redesigning the image acquisition system may be necessary instead of using augmentation to teach an unrealistic cue. Correctly identifying the source of missing information before training the model is an important engineering decision.
3. What is a hard negative?
A hard negative is an example that should be considered normal for the actual decision but that the model tends to flag as positive because its appearance resembles a defect. Examples include glare, shadows, machining marks, acceptable texture variations, a normal surface mistaken for staining, or dirt on the camera. Losing hard negatives within a general 'defect-free' pool makes error analysis more difficult.
Suppose, for example, that a thin white line appears on a shiny metal surface. This line could be a real scratch, a machining groove in the surface, or simply a reflection of light. These three visually similar situations require different production decisions. The labeling team should distinguish hard negatives under expert supervision, using different lighting or physical inspection when necessary. Treating an example as defective merely because the model assigned a high score creates a circular error.
Hard negative mining is the targeted examination of examples that the model falsely flags as positive and an expert confirms as normal, followed by incorporating suitable examples into training. Random normal examples can be selected initially, followed by reliably normal examples that the model most frequently confuses. However, collecting only high-scoring false positives can make the rest of the normal data distribution invisible. Maintain representation of random normal examples and different production conditions.

4. Why should recall, precision, and false alarms be evaluated together?
Recall indicates how many of the actual defective items are detected. Precision indicates how many examples flagged as defective actually are defective. The two measures answer different questions: one focuses on missed defects, the other on the reliability of an alert. For rare events, precision is highly sensitive to actual defect prevalence and the false positive rate.
Suppose 10 out of 10,000 products are defective. A system with a 90 percent defect detection rate and a 1 percent false positive rate detects about nine defective products. However, it also incorrectly flags approximately 100 good products. Of about 109 products flagged as positive, only nine are defective; precision is approximately 8 percent. This result shows why a model can generate a large operator review workload despite having 90 percent recall.
Costs differ if the field decision is 'reject the part directly' rather than 'route it to a second station.' The threshold is selected according to this workflow. In some applications, false alarms are easy to check, but a missed crack poses a high risk. On another line, a high false rejection rate could bring production to a halt. A single F1 score does not directly represent these costs.
5. Interactive example: How does defect prevalence affect alert quality?
The following calculation shows approximately how many true and false alerts can be expected in 10,000 parts for your chosen defect prevalence, detection rate, and false positive rate. These values are a mathematical example assuming a fixed model. In practice, when defect prevalence changes, sensitivity and the false positive rate may also change depending on production conditions.
These are expected values, not integers or actual field measurements. Calculation: TP=N·prevalence·recall; FP=N·(1−prevalence)·FPR.
In the interactive area, try reducing defect prevalence in particular. You will see that the reliability of positive predictions can fall even when recall and the false positive rate remain the same. Precision obtained using balanced test images in a laboratory may therefore not directly explain daily alert quality on a line with low defect prevalence.
The unit in which you calculate results also matters. If three cameras inspect a part, the false positive probability per image is not the same as the false rejection rate per part. This calculation assumes a single decision unit. In a multi-camera system, how alerts are combined must be modeled separately.
6. How should rare defects be prioritized during data collection?
Collecting rare defects sometimes means waiting; at other times it requires searching production records, examining archives of rejected parts, or observing the relevant failure mechanism under controlled laboratory conditions. However, controlled defects should not be assumed to come from the same distribution as naturally occurring production defects. Working with process engineers who understand how a physical defect forms may be more useful than generating random synthetic images.
Set collection priorities along three dimensions rather than solely by sample count: the cost of the critical defect, the diversity of independent examples available, and the conditions in which the current model struggles. High-cost defects with poor coverage can be examined first. If a defect class comes from just one line and one shift, a few new, different batches may be more valuable than hundreds of similar copies of the same image.
An active collection approach can present images the model finds uncertain for expert review. However, searching for critical and rare defects solely according to model uncertainty is insufficient; the model may incorrectly assign some new defects a highly confident normal score. Random inspection, process-based sampling, and expert feedback should be used together.
7. Are oversampling and undersampling always a solution?
Oversampling means presenting examples from less common classes more frequently. Undersampling means using selected examples from the majority class less often. Both can change the relative influence of classes during training. However, oversampling does not create new defect types; repeating the same image can increase memorization. Undersampling can inadvertently remove important normal variations and hard negatives.
Class-weighted loss functions or sampling strategies can support learning of rare classes. However, no particular method can be said to perform better on every dataset. Especially when label noise accompanies imbalanced data, excessively weighting a mislabeled rare example can have adverse effects. Evaluate label quality and independent defect diversity first.
Do not compromise data splitting discipline when using a sampling strategy. Leaving an augmented copy of an image from a rare class in the test set is leakage. Resampling and augmentation should be applied only to the training partition; the test structure set aside to represent natural prevalence should be preserved as far as possible.
8. How do you establish a hard negative mining workflow?
First, images incorrectly flagged as positive by the model are recorded separately. They are not automatically considered 'hard negatives,' since some may be actual defects or ambiguous cases. A quality expert reviews them and separates truly acceptable normal examples. The camera station, product, lighting profile, and identifiers of similar error examples are retained for each example.
Errors can then be clustered by visual cause: glare, machine oil, turning marks, shadows, edge regions, or incorrect focus. The aim is to find recurring root causes rather than collect the greatest number of false positive examples. For example, if most errors occur at a particular lighting angle, correcting the optical setup may remove the need to collect thousands of hard negatives.
Expert-verified examples can be added to the training pool. Their effect should be tested on new, independent normal examples. Improvement only on previously misflagged examples is not sufficient; the model may have memorized them. In particular, check whether false positives have been reduced without losing coverage of new, naturally occurring normal variations.
This loop brings label quality, the model, and image acquisition design to the same table. Hard negative mining is not merely a machine learning method; it is an organized process of learning from the field.
9. The PR curve, ROC curve, and decision threshold
For imbalanced problems, the precision-recall (PR) curve often provides a useful perspective because it shows how many positive decisions are correct at different thresholds. The ROC curve shows the relationship between sensitivity and the false positive rate. None of these measures determines production costs on its own. Especially at very low prevalence, even small false positive rates can create an operational burden.
As the threshold rises, false positives decrease in most models while the risk of missing some actual defects increases. Lowering the threshold can increase sensitivity but may create more false alarms. The appropriate threshold depends on factors such as quality risk, operator capacity, the behavior of the sorting system, and the type of critical defect. It should be determined on a separate validation set rather than by repeatedly using the test set.
With multiple defect classes, a single overall threshold may not be suitable in every case. A strategy could prioritize sensitivity for critical cracks and secondary inspection for removable stains. However, class-specific thresholds make the system more complex; each decision must be documented in the acceptance procedure.
10. The cost of false rejection and the cost of missing defects
Cost analysis is not limited to the unit price of the product. A falsely rejected part may undergo manual inspection, be reworked, or be scrapped outright. Missing a critical defect, on the other hand, may lead to customer returns, equipment failure, recalls, or safety risks. Treating these two error types as having equal cost is inappropriate, especially in safety-critical applications.
When preparing a decision matrix, distinguish the actions: acceptance, rejection, reimaging, and human review. Treating 'uncertain' as immediate rejection may not always be a good solution. Retaking an image may be more appropriate if image quality is inadequate; different lighting or physical measurement may be better if surface visibility is unclear; expert advice may be needed if the label definition is ambiguous.
Account for uncertainty in rare events when setting the threshold. Detecting all three critical defects in a test looks like 100 percent recall, but just three examples do not establish a very high level of assurance. The amount of evidence required for production acceptance should be decided together with the risk assessment and relevant industry procedures.
11. Why must critical defect classes be examined separately?
The 'overall defect' metric may look good while one subclass is systematically missed. When scratches, dents, cracks, and missing parts are combined under a single positive label, the model can raise its overall score by learning the majority defect type well. Failure on critical but rare cracks may remain hidden. Error analysis should therefore be performed by defect type, severity, location, and production condition.
Some classes may look similar yet differ from a business perspective. Oil stains and surface cracks may initially share an 'anomaly' label, but the system may later need more detail if rejection decisions differ. Increasing the number of classes is not an automatic solution either. Without sufficient independent examples for each class, a multiclass model can become more fragile. Consider a hierarchical decision structure or two-stage inspection first.
Critical defects require targeted tests, an archive of independently expert-approved examples, and, where possible, external validation from different production conditions. Success on a benchmark dataset does not mean production standards are automatically met.
12. How do you proceed if a rare defect has never been observed?
When no real defect examples are available, anomaly detection that learns from normal data can be a useful starting point. This approach learns features of normal appearance and attempts to flag substantial deviations. However, it is not guaranteed to detect every important defect; in particular, variable normal textures or normal marks resembling unseen defects can generate false alarms. An anomaly score is not a direct decision that 'the product is defective.'
Open research datasets such as MVTec AD are valuable for learning and comparing methods, but may not represent the material, imaging system, and defect rate of your own production line. Licensing terms and data use restrictions must also be considered. Controlled production, historical quality archives, and physical test results can be used for rare defects; the representativeness of every source should be reported explicitly.
Especially in safety-critical applications, the inference that 'the model knows normal examples well, so it will detect all abnormalities' is incorrect. An internal crack invisible in the image may require another measurement technology. Greater model complexity does not create missing physical information.
13. Example scenario: 10 defects in 10,000 parts
Assume that 10 of every 10,000 parts on a line are defective. Let the model have a 90 percent defect detection rate and a 1 percent rate of incorrectly flagging good parts. On average, nine actual defects are detected and one defect is missed. Of the 9,990 good parts, approximately 100 trigger false alarms. The total number of alerts is approximately 109. In this example, the probability of an actual defect per alert is slightly above 8 percent.
If the production team sees only 'recall is 90 percent,' it may assess the system's operational feasibility too optimistically. If an operator spends thirty seconds checking every false alarm, the daily workload grows. At the same time, the single missed critical defect may be extremely costly. The correct decision considers both aspects together rather than automatically choosing the fewest false alarms or the highest recall.
In an improvement experiment, suppose the false positive rate is reduced from 1 percent to 0.2 percent. If recall remains unchanged, the average number of false alerts among 9,990 good parts falls to about 20. Alert reliability improves substantially. However, in real models, a threshold change can affect recall as well. Both values must therefore be measured together and verified in an independent test.
14. How should a sound rare defect evaluation be reported?
For each critical class, the report should explain the number of independent parts, defect prevalence, recall, false positive rate, precision, and the relevant decision unit. Uncertainty intervals should be provided where possible. A success figure should not be reported for a class never seen in the test; instead, state 'insufficient evaluation data.' This honest limitation is more valuable than concealing production risk.
The causes of false alarms should also be listed. Are they glare, machining marks, or different product coatings? Each cause may require a different technical solution. Some errors are addressed by collecting data, some by the optical setup, some by threshold adjustment, and some by the label dictionary. A good report does more than provide scores; it guides the next engineering decision.
Conclusion: Imbalanced data is not merely a ratio to correct. It is a problem of accurately representing the natural field distribution, critical defect risk, and false rejection costs. Deliberately collecting hard negatives, independently testing rare classes, and selecting the decision threshold together with production processes are the foundations of a sustainable solution.
15. Threshold optimization is not just a model problem
Lowering the decision threshold in an inspection system flags more images as suspect. The production implications can be significant: the automatic sorter may reach capacity, the operator review queue may grow, or unnecessary rework may begin. Raising the threshold, meanwhile, may increase the risk of missed defects. A threshold decision should therefore not be based solely on the point of highest F1 on the validation curve.
It is useful to calculate at least three different decision-threshold scenarios: automatic rejection, routing to a second station, and human review. In automatic rejection, a false positive directly incurs a quality cost. At a second station, the cost may be lower, but capacity is limited. In human review, the operator must be able to genuinely distinguish the defect and sustain attention under continuous alerts. The same model can therefore produce different economic outcomes in different workflows.
During validation, compare multiple threshold candidates on the same independent part groups; where possible, define separate error limits for critical defects. When a threshold is changed in the field, record the reason for the change, the model version, and the result of the new acceptance test. Raising a threshold solely to reduce costs may require an independent assessment of critical defect safety.
16. How can data distribution shift be confused with the rare defect problem?
Suppose the model's false alarm rate increases over a week. The first interpretation might be 'there are not enough hard negatives.' However, the cause could also be a new lighting angle, dirt on the camera glass, a material coating, or an exposure change after maintenance. In such a case, adding more images to training with normal labels may temporarily reduce symptoms while concealing the physical cause.
First, examine the distribution of false alarms by time, camera, product, and batch. If errors began after a particular date across all products, a data distribution change is a strong candidate. If they increased only for a new product family, expanded scope or a new natural appearance may be involved. If errors occur equally across different shifts, the class definition or model decision should be examined.
Labeled and unlabeled monitoring indicators are useful together for making this distinction. Changes in brightness histograms, sharpness, camera profiles, or embedding distributions can provide warnings, but do not by themselves mean the model is making mistakes. Shift indicators unsupported by field labels should be used to prioritize investigation, not to establish a diagnosis.
17. Statistical uncertainty in rare defects
If a critical class has only ten independent defect examples, detecting nine means an observed recall of 90 percent. This observation, however, does not mean that true recall is exactly 90 percent. With few examples, uncertainty is wide. Percentages for critical defects should therefore always include the numerator and denominator: '9/10' is more informative than '90%.'
If defect examples come from the same machine or production batch, ten images may not count as ten independent conditions. As the independent unit becomes smaller, confidence intervals and generalization claims must be treated more carefully. The confidence level required for production acceptance may be determined by the risk assessment and relevant quality standard; substituting an arbitrary minimum sample count is not appropriate.
Deliberately collecting rare defects more frequently is useful for enriching a test, but it changes the actual prevalence in that test. An enriched test can be used for recall and defect-type analysis; production prevalence is additionally needed to estimate precision in the field. Presenting these two sources of evidence together better informs the decision-maker.
18. How do you prepare a sound experimental comparison?
Suppose you will compare four approaches: training with the original distribution, class weighting, rare-class oversampling, and hard negative mining. The experiments must be evaluated on the same independent test part groups. Data cleaning, label version, and optical profile should be held constant; otherwise, it becomes difficult to separate the cause of a performance change from the method. Parameter searches should be performed on the validation set, not the test set.
The comparison should not focus only on the overall score. Critical-class recall, false positive rate, review cost per product, errors across shifts, and coverage of rare defect subtypes can be reported separately. If an approach increases recall but doubles false rejections, it may offer no business benefit. In a second stage, error examples should be examined according to their physical causes.
An improvement in one experiment is not proof of general superiority. The result applies to the data and production setup used. Different production batches, camera changes, or new coatings may require revalidation. The most valuable experimental output is not the statement 'this method is always good,' but a clear demonstration of what improved and under which conditions.
19. An operational loop for data collection and human inspection
Collect field false positive and false negative examples in a review pool. Each record should include the image, part identifier, model version, decision score, camera conditions, and an expert decision where possible. Group errors by class, product, and root cause rather than reducing them to daily counts. Account for changes in line speed or defect prevalence when comparing data from the first and second weeks.
Although continually adding new examples to training may seem appealing, every new model version brings maintenance and validation work. First determine which problem you expect the new data to solve. If hundreds of collected false positives are copies of the same glare pattern, an optical intervention may be more effective. A few real but new crack examples, by contrast, may be more important for model coverage.
After an update, also verify that critical classes that previously performed well have not deteriorated. While reducing false alarms, hard negative mining must not cause the model to start treating actual defects as normal. A protected regression test containing negative and positive examples potentially affected by the changes is therefore necessary. Such a process may seem slower than accumulating random data, but produces more reliable results in production.
20. Setting an operational target between defect detection and false alarms
A model's technical target and business target may not be the same number. While the technical team tries to increase critical defect recall, the production team may ask how many parts will unnecessarily be sent to an inspection station each hour. Linking the alert count to line speed during model evaluation is therefore useful. For example, on a line processing 20,000 parts per hour, a false alarm rate of five per thousand good parts may create an additional inspection workload of approximately one hundred parts. If the workflow lacks this capacity, the system's practical feasibility is limited even if its model score is high.
On the other hand, missing critical defects solely to reduce the number of false alarms may be unacceptable. On some lines, alert and rejection levels can be designed separately: high-risk images are automatically sorted out, while borderline cases are routed to a second station. This solution must also be validated against human and hardware capacity. The thresholds that convert model scores into business decisions are part of the production process.
For such a decision, the error burden should be shown separately for different product families and shifts. An overall average may hide an unacceptable backlog in one shift. When the results report presents the number of missed defects of each type together with false rejection costs, managers can understand the trade-off being made.
An example comparison should also state the system's expected daily production volume. At a facility processing one hundred thousand parts per day, a 0.1 percent false positive rate can mean about one hundred additional reviews if defect prevalence is very low. The same rate means about one additional review on a line processing only one thousand parts. Even with identical rates, operational implications differ. Error clustering should also be checked: if all false alarms are concentrated in one shift, the overall FPR hides when the problem occurs.
If a combined cost calculation is made for missing a critical defect and falsely rejecting a normal part, the cost assumptions used must be stated explicitly. Rework after rejection, downtime, customer returns, and safety consequences may not all be known with the same certainty. Decisions become more reliable when the evaluation makes this uncertainty visible.
Frequently asked questions
Why can accuracy be misleading with class imbalance?
Because when the very frequent normal class is predicted correctly, missed rare defects have little visibility in overall accuracy. Class-specific recall, false positive rate, precision, and production costs should be examined together.
Is reducing normal examples always useful?
No. Undersampling can remove important visual diversity and hard negatives from the normal class. It can be tested alongside the training method, but should not distort the natural distribution of independent test data.
Can we label a hard negative example automatically?
Normal candidates assigned a high defect score by the model can be submitted for review. However, they should not be considered hard negatives until an expert or appropriate verification confirms they are genuinely normal.
How many examples are enough for a rare defect?
There is no fixed number. Defect diversity, acceptable risk, image acquisition conditions, and the target uncertainty level determine the requirement. The number of independent physical examples is more meaningful than image count alone.
Sources and technical references
The links are primary dataset and tool documentation relevant to the topic. Illustrative numbers and original drawings are used for educational purposes in the indicated areas.