smartyfy.mrindigi.com

AI & Machine Learning Master Course — 032. Exploratory analysis without test-set contamination

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 032: Exploratory analysis without test-set contamination

Prerequisites: Lesson 031. Learning outcome: Explore development data using targeted questions and documented decisions.

1. Explore with a question and a boundary

Exploratory data analysis helps us understand the development data before choosing modeling steps. It can reveal impossible values, skewed distributions, inconsistent categories, class imbalance, and relationships worth investigating. Exploration also influences decisions. If we repeatedly inspect the final test set while making those decisions, its role as independent evidence is lost.

Choose a partition strategy from the intended deployment setting before looking for promising relationships. Independent future parcels may support a random split. New-customer generalization requires customer separation. Forecasting requires chronological boundaries and realistic label availability. A random split is not automatically honest merely because its seed is fixed.

Maintain three roles: training data for fitting, validation data for development comparisons, and a final test set for a frozen evaluation. Cross-validation can organize the development stage, but a held-out test still needs protection. If data are scarce, use an appropriately nested evaluation design and be clear that it estimates the selection procedure rather than a model secretly tuned on outer folds.

Training feeds exploration and fitting. Validation feeds a development comparison that can revise the procedure; fitting still uses training rows. Once development ends, the pipeline is frozen. The separately reserved final test enters only final evaluation and the final report, with no tuning feedback.
Training and validation inform development choices. The final test evaluates the frozen procedure, with a partition design that respects relevant time or group structure. Open full-size diagram

2. Start with targeted quality questions

For a parcel-duration task, begin with questions such as: Are masses in consistent units? How often are features missing? Do item counts include zeros? Are some warehouses absent? Does target duration contain implausible negative values? Each question should connect to a contract, sampling concern, or modeling choice, rather than an unstructured hunt for dramatic correlations.

Inspect counts and denominators together. Ten missing masses are a minor fraction of ten thousand parcels but most of a twelve-parcel subgroup. Look at unique identifiers, duplicate patterns, numeric quantiles, category frequencies, and collection periods. Distinguish a count of rows from a count of independent customers or shipments.

Plots can show distributions, paired relationships, and changing coverage over time. Label units and sample sizes. A scatterplot of mass against duration might suggest a nonlinear relationship, while a histogram may reveal a mixture of kilograms and grams. Neither plot proves causation. A warehouse or service-level difference can confound a visually persuasive trend.

3. Use summaries that expose their assumptions

Consider six training parcels with masses [1, 2, 3, missing, 5, 6] kilograms and durations [3, 5, 4, 7, 11, 13] hours. Mass is missing for one of six, approximately 16.7 percent. The median observed mass is 3, and the duration mean is 43/6, approximately 7.167. These are descriptive summaries of these six parcels, not automatically estimates for every future route.

When calculating a summary with missing values, state which observations contribute. The mean of five observed masses is 3.4. Replacing the missing value with zero before summarizing would produce 17/6, approximately 2.833, making “missing” appear to be an actual small parcel. Later imputation is a modeling choice; initial exploration should preserve missingness explicitly.

Comparing low-item and high-item groups may reveal a target pattern, but subgroup boundaries chosen after examining many options can exaggerate it. Mark such findings exploratory, record how the grouping was chosen, and check the resulting hypothesis using development validation. Do not treat an exploratory association as a predeclared confirmatory test.

4. Keep a decision log

Every consequential observation should lead to a documented decision or an explicit unresolved question. For example: “Training mass includes one missing value; compare median imputation with median-plus-indicator within cross-validation.” Record the evidence, candidate handling rule, rationale, and validation plan. This prevents undocumented notebook edits from silently becoming part of the model.

Learn transformation parameters only from training partitions. Even a median, a histogram-based bin boundary, or an outlier cutoff is a fitted quantity if estimated from data. Inside cross-validation, estimate it separately on each fold’s training portion, then apply it unchanged to that fold’s validation portion. Fitting once on all development rows before cross-validation leaks information across folds.

Not every check must be learned. A pre-existing rule that parcel mass must be positive can validate every partition if it was specified independently of evaluation outcomes. A schema check that a test file loads does not itself tune a model. But inspecting test distributions to choose transformations or thresholds turns that information into development feedback. Keep integrity checks predefined and separate from adaptive exploration.

5. Recognize when the test is no longer final

If the final test score disappoints and you revise the model in response, that set has entered development. The revised model needs fresh independent evaluation, or the report must disclose the reuse and resulting limitation. Calling the second score “final” does not restore independence. A secure split manifest and restricted test access make accidental reuse less likely.

Training and validation findings can also become stale when deployment changes. A later warehouse rollout or new measuring device may alter missingness and feature ranges. Record the data snapshot and relevant dates so reviewers know which population the exploration describes. Monitoring later drift is a separate process from searching the original test set for convenient explanations.

6. A minimal training-only exploration

This CPU example requires Python 3.10 or later and NumPy 1.24 or later, with no API key or paid service. The split manifest contains identifiers only; no validation or test feature values or labels are loaded. The code checks disjoint membership and prints missingness, observed median, and target mean for the training partition.

The expected output is ten assigned identifiers, a missing fraction of 0.167, median observed mass 3.0, and mean duration 7.167. The manifest check cannot establish correct chronology or absence of shared customers; those require the corresponding metadata and task-specific checks. A reproducible exploratory notebook should state both what it checked and what remains uncertain.

import numpy as np

splits = {"train": {"r01", "r02", "r03", "r04", "r05", "r06"},
          "validation": {"r07", "r08"}, "test": {"r09", "r10"}}
assert splits["train"].isdisjoint(splits["validation"])
assert splits["train"].isdisjoint(splits["test"])
assert splits["validation"].isdisjoint(splits["test"])
mass_train = np.array([1., 2., 3., np.nan, 5., 6.])
duration_train = np.array([3., 5., 4., 7., 11., 13.])
assert len(mass_train) == len(splits["train"])
print("assigned identifiers:", len(set.union(*splits.values())))
print("missing mass fraction:", round(np.isnan(mass_train).mean(), 3))
print("observed median mass:", np.nanmedian(mass_train))
print("mean duration:", round(duration_train.mean(), 3))

Practice: four questions with worked answers

1. A histogram of final test values suggests a log transform. Can you choose it and still call the test untouched?

Answer: No. The test distribution influenced the modeling choice. Use development data for that decision and obtain fresh independent evaluation for a revised final claim.

2. Compute observed mean mass for [1, 2, missing, 9].

Answer: The observed mean is (1 + 2 + 9)/3 = 4, with a missing fraction of 1/4. Replacing missing with zero would give 3 and alter the meaning of the summary.

3. A customer contributes records to both training and test, but the goal is prediction for new customers. What is wrong?

Answer: The partition does not match the generalization question. Group by customer so test customers are unseen during training, while preserving any necessary time ordering.

4. How should a cutoff estimated from training quantiles enter cross-validation?

Answer: Re-estimate it on each fold’s training portion, then apply it unchanged to that fold’s validation portion. A cutoff learned from all development data has seen the validation fold.

Knowledge check: five explained MCQs

1. Exploration should primarily guide decisions using: A. Development data. B. Repeated final-test inspection. C. Future labels unavailable at prediction.

Correct: A. The final test must remain independent of adaptive choices.

2. A missing-value summary needs: A. Only a count. B. Its denominator and meaning. C. A zero replacement first.

Correct: B. The fraction and missingness interpretation determine its relevance.

3. A predeclared schema integrity check on test data: A. Is automatically model tuning. B. Can differ from adaptive test exploration. C. Removes all leakage risks.

Correct: B. Its purpose and fixed rule matter; it must not become feedback for modeling choices.

4. A strong visual correlation proves causation: A. Yes. B. Only with a large sample. C. No.

Correct: C. Confounding and selection can create associations without the proposed causal effect.

5. After tuning in response to a final test score: A. The set becomes development evidence. B. Its independence is restored. C. Repeating the seed fixes it.

Correct: A. The outcome has influenced the model, regardless of the label assigned to the split.

Common pitfalls

Avoid broad test-set exploration, undocumented threshold searches, missing denominators, and plots that hide units or groups. Do not confuse row disjointness with independent entities or valid chronology. A split manifest protects membership, while the deployment question determines whether those memberships are meaningful.

Summary

Good exploration is targeted, reproducible, and bounded by the evaluation design. Summarize training data honestly, log decisions, and fit learned transformations inside training folds. Preserve the final test for the question it was created to answer: how a frozen procedure performs on independent examples.

Primary sources and further reading