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.| income_cat | full | random | stratified | random error | strat. 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.
"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).
# 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.
random_state=42 does not fix this. It picks one draw from the cloud and makes it repeatable. A repeatable unlucky test set is still unlucky.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.