data science / machine learning
Learn Machine Learning Free, Starting With the Mistake That Fakes 85% Accuracy
The most useful early lesson in machine learning is how a model can look excellent and know nothing. This page reproduces train/test leakage on pure random noise, shows the three-line fix, and then lays out the free courses and books in an order that teaches you to avoid it.
Most first-model tutorials end with a number like 92% and a feeling of success. The number is only worth anything if the model was tested on data it had no way of having seen, and "no way of having seen" is easier to violate than it sounds. Leakage is the usual culprit when a promising result collapses in production. It is also easy to demonstrate, so we start there instead of with the history of neural networks.
01 · THE EXPERIMENT
A classifier that beats chance on random noise
Build a dataset with 100 rows and 2,000 columns of random numbers, and labels that are coin flips. There is nothing to learn, so any honest accuracy must hover around 50%. Now do what looks like sensible preprocessing: pick the 20 columns that correlate best with the label, then cross-validate a logistic regression on just those.
import numpy as np from sklearn.feature_selection import SelectKBest, f_classif from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score from sklearn.pipeline import make_pipeline rng = np.random.default_rng(0) X = rng.normal(size=(100, 2000)) # pure noise y = rng.integers(0, 2, size=100) # labels unrelated to X # Leaky: the 20 columns are chosen using ALL 100 rows, test folds included X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y) print(cross_val_score(LogisticRegression(), X_sel, y, cv=5).mean()) # Honest: selection happens inside each training fold only pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression()) print(cross_val_score(pipe, X, y, cv=5).mean())
With seed 0 the two lines print 0.78 and 0.59. One seed on 100 rows is noisy, so the table repeats the whole experiment for seeds 0 to 19 and averages the results:
| Procedure | Mean accuracy | What it claims |
|---|---|---|
| Select features on all rows, then cross-validate | 0.85 (lowest single run 0.76) | A strong model |
| Select features inside each training fold (Pipeline) | 0.52 | Nothing, which is the truth |
The leaky version never looked at test labels directly. It simply used all 100 labels to decide which columns to keep. With 2,000 candidates, some columns correlate with the labels by luck, and picking them guarantees the test folds look predictable. The fitted model then scores 85% on noise.
02 · THE FIX
Fit every preprocessing step on training data only
The rule is short: split first, and let anything that learns from data (scalers, imputers, feature selectors, encoders, PCA) see only the training portion. In scikit-learn the clean way to enforce this is to put the steps in a Pipeline, as the second block above does. Cross-validation then refits the whole chain on each training fold and applies it unchanged to the held-out fold.
The scikit-learn documentation has a chapter on exactly this, and it is one of the best free pages in the library. It defines leakage as using information that would not be available at prediction time, and its first tip is to always split train and test subsets before any preprocessing.
- scikit-learn: common pitfalls and recommended practices ↗Includes a Data leakage section with examples and tips for avoiding it, plus guidance on why Pipelines help.scikit-learn.org
- scikit-learn: pipelines and composite estimators ↗Reference for chaining preprocessing and models into one estimator.scikit-learn.org
- scikit-learn: cross-validation ↗The folds, the scorers, and the iterators for grouped and time-ordered data.scikit-learn.org
03 · FIELD GUIDE
Five places leakage hides in real projects
| Pattern | Example | Defense |
|---|---|---|
| Preprocessing before the split | Scaling or imputing with statistics from the whole dataset | Pipeline, as above |
| Target leakage | A "refund_issued" column when predicting which orders get refunded | Ask of every column: would I know this at prediction time? |
| Time travel | Shuffling rows of time-ordered data, so tomorrow trains and yesterday tests | Split by date, test on the later period |
| Duplicate or related rows | The same customer appears in train and test | Deduplicate; split by customer ID |
| Repeated peeking | Tuning against the test set until it looks good | Hold out a final set you touch once |
04 · COURSES AND BOOKS
An order for the free material that builds on the lesson
The first two entries cover the basics and then leakage explicitly. The rest add breadth and theory.
- Kaggle Learn: Intro to Machine Learning ↗Your first decision tree and random forest, with exercises you run in the browser. Kaggle states its Learn courses cost nothing.kaggle.com
- Kaggle Learn: Intermediate Machine Learning ↗Missing values, categorical variables, pipelines, cross-validation, XGBoost and a lesson literally called Data Leakage. Kaggle estimates four hours.kaggle.com
- Google Machine Learning Crash Course ↗Self-contained modules on models, data, evaluation metrics such as precision, recall and AUC, and real-world deployment concerns.developers.google.com
- Machine Learning Specialization (Andrew Ng, DeepLearning.AI and Stanford Online) ↗A three-course program using NumPy and scikit-learn for supervised models, then TensorFlow, trees and unsupervised learning. Coursera lists an Enroll for free button, about two months at 10 hours a week, and financial aid; confirm what the free option includes on the page before you commit.coursera.org
- An Introduction to Statistical Learning (ISLR and ISLP) ↗The standard statistical-learning textbook. The site offers PDF downloads of the 2nd edition with R and of the Python edition (ISLP, published 2023), with a lab at the end of each chapter.statlearning.com
- Stanford CS229: Machine Learning ↗The course website, currently showing the Summer 2026 offering. Math-heavy; the stated prerequisites are Python/NumPy programming, probability theory, and multivariable calculus with linear algebra.cs229.stanford.edu
- CS229 lectures, Autumn 2018 (YouTube) ↗The recorded lecture series from Stanford's machine learning course, led by Andrew Ng.youtube.com
05 · TRY IT
Break your own model on purpose
06 · FAQ
Frequently asked questions
What is data leakage in machine learning?
Leakage means information that would not be available at prediction time influenced the model's training or evaluation. It makes test scores look better than real performance. Common sources are preprocessing fitted on all the data, columns that encode the answer, and splits that ignore time or duplicates.
How do I avoid leakage when using scikit-learn?
Split your data first, then put every step that learns from data inside a Pipeline so it is fitted on training folds only. Cross-validate the pipeline, not pre-transformed data, and keep a final hold-out set that you evaluate once.
Where should a beginner start learning machine learning for free?
Start with Kaggle's Intro to Machine Learning and Intermediate Machine Learning micro-courses, which run in the browser and cover pipelines, cross-validation and data leakage. Then take a longer course such as the Machine Learning Specialization or Google's Machine Learning Crash Course.
Do I need advanced math for machine learning?
Not to build and evaluate models with scikit-learn, but you need basic statistics to judge results honestly. Calculus and linear algebra become necessary for courses like Stanford CS229, whose stated prerequisites include probability theory, multivariable calculus and linear algebra.