COSC 3430 · Artificial Intelligence

Random vs. Stratified Test Sets

Set aside a test set from the California housing districts, again and again. Each draw is made twice: purely at random, as train_test_split does by default, and stratified by income_cat. Watch how much the income mix of the random test sets wobbles, and how little the stratified ones do.
Dataset
Test set size
—
Draw test sets

The income mix: full dataset vs. the last test set

full dataset random test set stratified test set
income_catfullrandomstratifiedrandom errorstrat. error

Shares in percent of each set; errors relative to the full dataset, as in Géron's comparison table. Click a row (or a group of bars) to follow that category below.

Every draw so far, for one category

random test sets stratified test sets share in the full dataset
test sets drawn0
random
range—
std. dev. (observed)—
std. dev. (formula)—
average miss—
stratified
range—
std. dev. (observed)—
rows from this category—
average miss—

"Average miss" is how far a test set's share of this category lies from the full dataset's share, on average, as a fraction of that share: 10% means a true share of 4.0% typically comes out as 3.6% or 4.4%. The formula is the one from class: Var = p(1−p)/n · (N−n)/(N−1).

The two splits in code

# random: the income mix of the test set is left to chance
train_set, test_set = train_test_split(
    housing_full, test_size=0.2, random_state=42)

# stratified: same share of every income category in both sets
strat_train_set, strat_test_set = train_test_split(
    housing_full, test_size=0.2,
    stratify=housing_full["income_cat"], random_state=42)

The page draws the same way: the random split picks rows uniformly from the whole dataset; the stratified split first fixes how many rows each income category gets (its share of the test set, rounded to whole rows, as scikit-learn does), then picks those rows at random within the category.

Reading the spread

Built to accompany COSC 3430 (Artificial Intelligence), end-to-end ML project, part 3 (creating a test set). Category counts are those of the California housing data used in class (income_cat from pd.cut with bins 0, 1.5, 3, 4.5, 6, ∞); the draws are simulated live in your browser.