Article sections
1. Which questions do train, validation, and test sets answer?2. Why is random image splitting insufficient for most production problems?3. How do you design a group-based data split?4. When is a temporal split necessary?5. Data leakage is not just the same file appearing in two sets6. When and in what order should data augmentation be applied?7. Preserve class balance or reflect real prevalence?8. Designing three separate evaluation questions9. Post-split checks: How do you test for leakage?10. Numerical example: The difference between random and group-based splitting11. Validation with external data and distribution shift12. What should a good experiment report explain?13. Practical data splitting checklist14. Cross-validation pitfalls in small datasets15. Why should model selection and final testing be kept separate?16. Finding hidden group keys specific to the production line17. Evaluation at the decision level, not the image levelFrequently asked questionsA model can have a test accuracy of 99 percent and still fail significantly on a new production batch. One important reason is that the training and test data are not truly independent. When frames from the same part, nearly identical images from the same production session, or label-related metadata are accidentally distributed across different sets, the model may memorize familiar examples instead of generalizing to new conditions.
Data splitting is not merely choosing ratios such as 70/15/15. The real decision concerns which observations will be considered independent of one another and which real use case the test set will represent. This guide compares random, group-based, temporal, and external-environment evaluation, and offers practical checks for identifying and preventing data leakage. The numerical examples are instructional, not measured results from an actual model.
1. Which questions do train, validation, and test sets answer?
The training set is used to learn model parameters. The validation set supports development decisions such as model selection, hyperparameter search, and setting the decision threshold. The test set is used to obtain the final performance estimate on previously unused examples after development decisions are complete. Mixing these roles can overstate the model's measured performance.
For example, when you repeatedly run experiments on the same test set and choose the best result, your decisions adapt to the test set even if you do not train directly on the test labels. The test set is no longer an independent final examination. In that case, a new, protected evaluation set may be needed. Data splitting decisions should be made before the experiment begins, not continually redesigned based on test set results.
Commonly used ratios such as 70/15/15 or 80/10/10 are not universal rules. Data volume, the number of independent parts, rare defects, and the evaluation objective matter more than the ratios. In a dataset containing one hundred thousand images but only one hundred independent parts, the effective sample size is not equal to the number of images.
The critical question is: In what future situation do we want the system to work? A new batch on the same line, a different camera, or a product from a new supplier? The test should be designed around this question.
2. Why is random image splitting insufficient for most production problems?
Consecutive images taken by a production-line camera are highly similar. If you split them entirely at random, some frames of the same product may end up in training and others in testing. When the model sees the same scratch location, background, or lighting pattern again, the test score rises. But this does not mean it can recognize a new physical part.
A high record count does not reduce this risk. On the contrary, collecting many frames per part can increase the likelihood of training-like images appearing in the test set under random splitting. Different angles of the same object or several magnifications of the same surface are also related examples. If the relationship is not clear from the filename, perceptual similarity screening may be needed to find candidates.
For example, suppose 20 images are taken of each of 100 parts. There are 2,000 files in total, but physical product diversity is limited to 100 parts. When images are split randomly, it is unlikely that nearly all images of a part will remain in only one set. With group-based splitting, all images of each part are kept in the same split. A harder test is not necessarily undesirable; it may indicate a more honest evaluation.

3. How do you design a group-based data split?
A group is a key indicating that multiple images come from a shared, dependent source. The most common example is the part ID; however, a production batch, session, camera station, or higher-level identifiers such as patient/object IDs can also serve as groups. Which group you use depends on your evaluation objective. A part ID may be more appropriate for generalization to new parts, while a batch ID may be more appropriate for generalization to new batches.
A single grouping level may not address every risk. Parts produced in the same batch share material and processing conditions. Train and test sets separated by part do not fully measure generalization to new batches if batches appear on both sides. The part and batch hierarchy must therefore be preserved. In some projects, two separate tests can be performed: new parts from previously seen batches and entirely unseen batches.
Splitters such as GroupShuffleSplit or GroupKFold are designed to prevent groups from being broken apart. However, they may not automatically maintain defect class balance. StratifiedGroupKFold aims to approximately balance class proportions while preserving group integrity; however, exact balance is impossible if there are too few groups or group distributions differ greatly. If a class occurs in only one batch, independent evaluation is limited regardless of the method used.
In the absence of metadata, group definitions can be inferred retrospectively, but these inferences carry risks. Grouping by imaging session can provide partial protection when the actual part ID is unknown; it is not a guarantee of complete independence.
Examining group leakage visually
The tool below shows the difference between image-based and part-based data splitting in an illustrative example with three images taken of each part. The values you see are calculated from which sets the examples enter, not from an actual model score.
The letters A-D represent four physical parts, and the numbers 1-3 represent different frames of those parts. The sampling distribution was chosen for illustration.
4. When is a temporal split necessary?
The production environment changes over time. Camera alignment, lens cleanliness, lighting power, product surfaces, suppliers, and maintenance procedures may not remain the same. If the model will be used on parts produced in the future, a chronological test may be more realistic than randomly splitting past images. For example, the first three months can be allocated to development, the fourth month to validation, and the fifth month to independent testing.
The critical condition for this approach is that future data must not leak into training decisions. In systems where the same part is imaged again or labeled after a delay, looking only at the timestamp is insufficient. All images belonging to the production event must be kept together, and it must be clear whether the timestamp refers to image capture, uploading, or labeling.
When interpreting temporal test results, two possibilities must be distinguished: the model's general error and a genuine change in the production distribution. If a new defect type appears in a future period, this differs from ordinary generalization error. The test report should describe the nature of the new condition; the result should not be reduced to a single accuracy percentage.
Temporal splitting can be combined with group-based splitting. For example, next month's batches are set aside for testing, and no part from those batches appears in training. The evaluation thus tests independence in terms of both time and physical products.
5. Data leakage is not just the same file appearing in two sets
Leakage occurs when information that should not be accessible during evaluation is carried into training or development decisions. The clearest example is the same file appearing in two splits. In more subtle cases, near duplicates, product IDs, batch-specific labels, preprocessing statistics, or quality records created in the future may make the model's job easier. If this information is unavailable in production, the performance estimate may become invalid.
For example, if the mean and standard deviation of all data are calculated before splitting into train/test, the test distribution has contributed to preprocessing. This may not cause a large error in every case, but in principle, transformations learned from data must be fitted only on the training portion. The same rule applies to feature selection, threshold tuning, normalization parameters, and learning-based methods used in data cleaning.
Another risk is that the class can be inferred from the file path. If the image name contains rejected and a workflow indirectly passes this information to the model, the model may learn file information rather than the visual appearance of the defect. Fields such as a quality outcome produced after labeling or an operator intervention can also accidentally become features.
The best question for a leakage audit is: Is this information available at decision time in actual production? If not, it must not enter the training input; it should be retained only as audit or external validation information.
6. When and in what order should data augmentation be applied?
Augmentation can be considered at two different stages: applying random transformations to images during training or generating many derived images in advance. In both cases, the data should first be split while preserving independent groups, and augmentation should then be performed only on the training portion. If the original image is in training and its rotated copy is in testing, the two sets are not independent.
Operations required by the model, such as deterministic resizing or normalization, can be applied to the validation and test sets. However, the parameters of these transformations must be specified externally or learned only from training data. Searching for special transformations that make test performance look good also defeats the purpose of the test.
The original image to which each augmented derivative belongs must also be recorded. If several variations of the same image remain within training, the number of independent examples has not increased; only the visual variation the model can see has expanded. The experiment report should give separate counts for raw images, independent parts, and augmented examples.
7. Preserve class balance or reflect real prevalence?
Balancing the training data can make learning easier, especially for rare defects. However, if defect prevalence in the test set differs greatly from the actual production rate, you may not be able to estimate the model's false-alarm burden correctly. For example, a test containing 50 percent defective images does not directly represent the reliability of positive predictions on a production line with a defect rate of one in a thousand.
For this reason, the primary field-performance test should preserve the natural distribution of the target production conditions whenever possible. A separate challenging-case set is useful for examining rare defects more intensively. These two tests answer different questions; their results should not be blended into a single number. While a balanced test set helps reveal technical sensitivity to rare defects, a natural-distribution test reflects the operational decision burden.
If group integrity prevents defect rates from being equalized perfectly, do not create artificial balance by splitting groups apart. Report the number of independent groups alongside class counts. If a rare class appears in only two batches, evidence for its field generalization is limited even if a five-fold evaluation looks strong.
8. Designing three separate evaluation questions
A reliable project does not have to squeeze everything into a single test set. The first test can answer the question of "generalization to new parts under previously seen production conditions". A second can measure robustness using new production batches or images from a later date. A third can examine transfer to a different camera or facility. Each test represents a different distribution; expecting the same performance on all of them is unrealistic.
What matters is defining each test in advance. Removing a batch on which the model failed after the fact to make the results look higher changes the purpose of the evaluation. If the test scope has to change, old and new results must be reported as different evaluation versions. The reason for excluding a condition must be stated explicitly.
Failure on a new-facility test does not mean the model is entirely useless, but it reveals the limits of its transferability. Similarly, a very good random-test result does not prove that a new camera will deliver the same result. The report needs to explain this difference in scope to the reader.
9. Post-split checks: How do you test for leakage?
The first check is simple: Do separate sets contain the same image ID, part ID, or a batch ID that must not be split? File hashes are then compared. Once identical files have been detected, perceptual similarity or embedding-based candidate screening can be performed for near duplicates. Candidate pairs may require human review; two very similar but distinct parts are not the same image.
Metadata is also examined during split checks. If one camera station captures only defective parts and another camera captures only normal parts, the model may learn camera differences rather than product defects. A training/test split does not eliminate this bias; the data collection design may need correction. Similarly, if all parts from one supplier are defective, the supplier's texture can become a proxy variable for the defect label.
It is not possible to eliminate data leakage completely with just one tool. ID-based auditing, near-duplicate screening, preprocessing review, feature/metadata checks, and independent process review should be used together. Deliberately hiding the test set can sometimes help, but those responsible for the experiment must be able to understand data provenance and perform the necessary independence checks.
Think of the splitting policy as a contract: Which IDs will be kept separate, what date marks the start of testing, what happens when a new product arrives, and will the test be redefined after a label revision? If these questions are not documented, two engineers may draw different conclusions from the same dataset.
10. Numerical example: The difference between random and group-based splitting
Suppose a total of 9,000 images have been taken of 300 physical parts. Each part has thirty closely similar frames. A completely random split of 80 percent training and 20 percent testing looks balanced in terms of image count. However, most parts in the test set also have frames in training. If your claimed evaluation objective is recognizing defects on new parts, this is not an appropriate design.
With a group-based approach, 240 parts can be allocated to training and 60 parts to testing. All frames of the same part then remain on only one side. Although the test set contains 1,800 images, the number of independent parts is 60. Part-level dependence must also be considered when reporting results with confidence intervals; treating frames as independent can understate uncertainty.
The measured scores of the two strategies may differ, but no particular percentage difference can be predicted in advance. The high/low scores shown in the visual example are only there to explain the method. The real consequence is that the question being tested changes: Random image splitting may better assess recognition of similar images, while group-based splitting may better assess generalization to new parts.
11. Validation with external data and distribution shift
An external validation dataset can come from new production conditions outside the training system's direct control. Scenarios such as a different factory, a different camera, or a new supplier are particularly valuable. However, using the term "external" does not by itself ensure complete independence. Imaging the same physical parts again at another station can create hidden relationships. Data provenance must therefore be checked in the external set as well.
The measurement protocol must be consistent when comparing against external data. If scratches are labeled through physical measurement in one set and only through visual estimation in another, directly comparing the results is misleading. Different lighting or resolution can affect performance on their own; these should be stated separately in the report. Limited transfer performance is a genuine engineering finding.
If the model is updated after an external test, the same data now becomes part of the adaptation process. Another held-out period or group may be needed to validate the new version in a truly independent way. In continual-learning setups, this boundary is managed more carefully.
12. What should a good experiment report explain?
The report should include not only train, validation, and test percentages, but also the splitting unit. How many images, independent parts, and production batches are there? What are the time intervals? Which cameras and product families were used? Was defect prevalence left natural in the test set or changed through sampling? On which side was data augmentation applied? How many times was the test set examined?
Evaluation metrics should be calculated, wherever possible, at the unit on which the decision is applied. For a part-rejection system, high frame-level accuracy may not explain the part-level decision. If several frames are taken of one part, how are they combined? Part-level false-rejection and missed-defect rates may also be needed.
When reporting uncertainty, pay attention to the number of independent groups. Counting errors from thirty frames of the same part as separate events can artificially narrow the confidence interval. Group-level resampling or appropriate statistical methods may be more realistic. The numerical method, data dependence, and quantity being estimated must be chosen together.
13. Practical data splitting checklist
First, write the evaluation objective in a single sentence, for example, "Generalization to parts from a new production batch". Choose the group key based on that sentence. Freeze a snapshot of the source dataset, parse the IDs, set aside the test sets, and establish the validation strategy within the training data. Do not perform model selection or transformation tuning on test data.
Then audit overlapping groups, exact duplicates, near-duplicate candidates, temporal boundaries, and metadata-based leakage paths. Report which groups contain each defect class; do not generalize the result if a rare class is entirely absent from the independent test. If needed, also prepare a challenge-focused evaluation set, but state that it is not a natural-distribution test.
Finally, retain the test policy. It should be clear under which conditions a new test is required when a camera changes, a product is revised, or the label dictionary is updated. Test design may be more tedious than it looks, but it is what makes the time spent choosing a better architecture meaningful. A reliable test tells you not how good the model looks, but under which conditions and to what extent it can be trusted.
14. Cross-validation pitfalls in small datasets
When the number of independent parts is small, the result can be highly sensitive to a single train/test split. Especially when defective parts are concentrated in a few groups, which group ends up in testing can substantially change performance. Group-based cross-validation helps show results across different group combinations, but ensuring that each fold is truly independent still depends on the group definition.
Folds being approximately equal in size does not mean they contain the same number of defects. If a class occurs in only three production batches, some folds in a five-fold design may contain none of that class. In this situation, replacing undefined metrics with zero or hiding missing folds leads to misinterpretation. Which classes appear in which folds must be reported transparently.
Breaking groups apart to balance the class distribution produces a neater table in the short term, but violates the principle of independence. Choosing fewer folds, conducting separate evaluations for specific classes, or collecting additional independent production batches may be more honest solutions. With limited data, good uncertainty reporting is more valuable than a single high average.
15. Why should model selection and final testing be kept separate?
Model selection is not just choosing an architecture. Learning rate, augmentation strength, threshold, image size, filtering, and different error-cost weights are also development decisions. Adjusting each of these decisions by looking at test results means incorporating the test into development. As a result, the selected model can be expected to look good on the test, but whether the same success will continue on new data is more uncertain.
This is why the validation set is set aside for experimentation and the test set for estimating final performance. Multiple validation experiments can be performed, and the parameters under investigation are recorded. If an unexpected error appears in the test results, it should of course be reported and analyzed. However, if the model is changed using this information, the old test is no longer an independent final evaluation of the new version.
In production, budget constraints may make it impossible to collect new test data every day. In that case, protected time windows, periodic test batches, or external field evaluation can be used to define the limits of decisions. What matters is honestly explaining how independent the evidence used actually is.
16. Finding hidden group keys specific to the production line
Sometimes the most important group key is not directly available in the database. Metal parts cut from the same coil, products made in the same mold cycle, parts secured in a shared fixture, or sessions using the same camera settings may be related in appearance. Finding all these relationships through image similarity alone is difficult; it requires the production engineer's process knowledge.
If the dataset contains part IDs but no batch IDs, records from different parts sharing the same surface texture may fall into different splits. This creates a problem for a new-batch objective. Similarly, if a camera images all defective parts for manual reinspection, the camera can become associated with the label. If station-specific lighting or background traces appear in the image, the model may exploit the wrong cue.
In a data review meeting, it is useful to tabulate machine, mold, batch, shift, session, material, and camera fields and discuss the level at which common causes exist. There is no single "correct" group; independence must be established at the level of the conditions to which generalization is expected.
17. Evaluation at the decision level, not the image level
Suppose three images are taken of a part and the system uses the rule "reject if there is a critical defect in any image". Even if the false-positive rate for a single image is low, combining three images can change the part-level false-rejection rate. Similarly, seeing the same defect in several images affects the probability of missing a defect. Evaluating these relationships requires joining images by part ID.
The output of a vision model can be used as an alert to the operator, a rejection command to a physical sorter, or a referral to a second measurement station. As the decision being made changes, so do the appropriate metric and test unit. A frame-level score alone may not explain how many intact parts will be separated out each hour in production.
When designing the test set, decide from the outset at which level results will be reported: image, defect region, part, or production batch. Multiple levels can be reported, but they have different independence assumptions. Stating this difference makes both engineering acceptance and tracking future changes easier.
At final delivery, it is also useful to retain the test split's ID list, group definition, and the data version from which it was created. Assigning the same groups to the same splits when the same code is run again allows direct comparison of experiments. If the evaluation policy changes, the new report should not overwrite the old one; both should be kept as separate versions.
Frequently asked questions
Must the train/validation/test ratio always be 70/15/15?
No. The ratios are not a fixed standard. The number of independent parts/batches, defect prevalence, and which generalization will be tested are more important. A small number of groups limits statistical confidence, especially for rare defects.
Can different angles of the same part be in different sets?
Generally not, if the objective is generalization to new parts. All images of the same part must be kept in the same group. Other designs can be considered only if there is a clearly different research question and this limitation is stated in the report.
Is class imbalance in the test set a problem?
Not by itself, if it reflects actual production prevalence. It may even be useful for assessing the false-rejection burden. An additional enriched challenge test can be performed for the rare class; the results of the two tests should not be mixed.
Does using cross-validation remove the need for a separate test set?
Cross-validation is useful for model selection and uncertainty analysis. When many design decisions are based on cross-validation results, a protected test set can still be valuable for final independent evaluation. Groups must also be preserved across cross-validation folds.
Sources and technical references
The links are to primary dataset and tool documentation on the topic. Illustrative numbers and original drawings have been used for educational purposes in the indicated areas.