Where the Course's Data Comes From
Every lesson needs rows to fit on, and this course takes them from two places only. scikit-learn ships six small toy datasets that load without any download, and it ships generators that make synthetic data of a chosen shape. On top of those, a short script of your own generates the two tables of the Rivermead Cycles scenario that the regression and classification modules use. Nothing is fetched from the internet after the setup lesson, nothing contains a real person, and every learner gets the same values because every random choice is seeded.
The Bundled Toy Datasets
| Loader | Rows by columns | Task | Target |
|---|---|---|---|
load_iris | 150 by 4 | classification | 3 species |
load_wine | 178 by 13 | classification | 3 cultivars |
load_breast_cancer | 569 by 30 | classification | 2 classes |
load_diabetes | 442 by 10 | regression | disease progression |
load_digits | 1,797 by 64 | classification | 10 digits |
load_linnerud | 20 by 3 | regression | 3 physiological measures |
Each loader returns a Bunch, a dictionary whose keys are also
attributes: data holds the features, target the labels or values,
feature_names and target_names the names, and DESCR a description.
Two options matter in this course. as_frame=True returns data as a
pandas DataFrame and target as a Series, with the names as columns, which
is what the preprocessing lessons want. return_X_y=True skips the Bunch
and returns the two arrays directly, which is enough when only numbers
matter, as in the contract lesson.
The Generators
sklearn.datasets also makes data to order, and each generator has a
random_state so that the same call gives the same rows every time:
make_classification(n_samples, n_features, n_informative, ...)builds a classification problem where some features carry signal and the rest are noise. The model-family lessons use it when a bundled set is too easy.make_regressiondoes the same for a numeric target, with a chosen noise level; the inspection module uses it to build a table with one duplicated feature.make_blobsdraws points around chosen centres, andmake_moonsdraws two interleaved crescents. Both appear in the clustering lessons, where the shape of the groups is the whole question.
What a Seed Controls
A random generator produces a sequence of numbers that looks random but is
fully determined by its starting value, the seed. Two seeds appear in
this course. numpy.random.default_rng(2026) creates NumPy's generator
with seed 2026; the course's own scripts draw every random value from it,
so the Rivermead tables are the same on every computer with the pinned
NumPy. random_state=0 is scikit-learn's version of the same idea: a
generator, a splitter or a model that uses randomness takes it, and the
same integer gives the same result. A seed fixes which random values are
drawn. It does not make the data less random in any other sense, and
changing it changes every value that was drawn after it while leaving
everything that was not random, such as the column names and the row count,
exactly as it was.
The Rivermead Generator
The generator writes two CSV files. demand.csv is four years of daily
rentals for a bike-share operator: each day has a temperature that follows
the season, rain on about a third of days, a weekend flag, a promotion flag
on about one day in ten, and a rentals count built from those with growth
over time and noise. docks.csv is one row per dock: its station, age in
months, uses per week (with 90 values missing), a model letter, a district
and whether it developed a fault within 30 days. The fault is drawn from a
probability that rises with age and use and is higher for model C and the
Harbour district, so there is a pattern for models to find and a known
answer to compare with.
The generator writes files rather than making the tables inside every lesson for two reasons. Every lesson then reads exactly the same rows, and a table on disk can be opened, inspected and reasoned about on its own.
Exercise: Load, Generate and Inspect
You will load a bundled dataset two ways, generate a classification problem, write the two Rivermead tables, and separate features from the target.
Starting state: the course environment, active in your terminal.
-
Create the lesson folder. macOS and Linux:
mkdir -p ~/sklearn-practice/load-bundled-and-generated-data cd ~/sklearn-practice/load-bundled-and-generated-dataWindows PowerShell:
mkdir $HOME\sklearn-practice\load-bundled-and-generated-data cd $HOME\sklearn-practice\load-bundled-and-generated-data -
Save this as
make_rivermead.py. Later lessons ask you to save the same file again in their own folders:"""Generate the Rivermead Cycles practice tables: daily demand and dock faults.""" import numpy as np import pandas as pd rng = np.random.default_rng(2026) # Daily demand: four years of days in date order. days = pd.date_range("2022-01-01", periods=1460, freq="D") season = np.sin((days.dayofyear.to_numpy() - 100) / 365 * 2 * np.pi) temp_c = 11 + 9 * season + rng.normal(0, 3, size=1460) rain_mm = np.where(rng.random(1460) < 0.35, rng.gamma(2.0, 3.0, size=1460), 0.0) weekend = (days.dayofweek >= 5).astype(int) promo = (rng.random(1460) < 0.1).astype(int) growth = np.arange(1460) * 0.25 rentals = 900 + 28 * temp_c - 9 * rain_mm + 180 * weekend + 240 * promo + growth + rng.normal(0, 90, size=1460) demand = pd.DataFrame({ "day": days, "temp_c": temp_c.round(1), "rain_mm": rain_mm.round(1), "weekend": weekend, "promo": promo, "rentals": rentals.round().astype(int), }) demand.to_csv("demand.csv", index=False) print("Wrote demand.csv:", demand.shape[0], "rows,", demand.shape[1], "columns") # Dock faults: one row per dock, with a station group and some missing usage. n = 3000 age_months = rng.integers(1, 121, size=n) uses_per_week = rng.gamma(3.0, 12.0, size=n).round(1) model = rng.choice(["A", "B", "C"], size=n, p=[0.5, 0.3, 0.2]) district = rng.choice(["Castle", "Harbour", "Meadow", "Station", "University"], size=n) station = rng.integers(1, 61, size=n) risk = -4.0 + 0.018 * age_months + 0.012 * uses_per_week + 0.7 * (model == "C") + 0.4 * (district == "Harbour") fault_30d = (rng.random(n) < 1 / (1 + np.exp(-risk))).astype(int) uses_per_week[rng.choice(n, size=90, replace=False)] = np.nan docks = pd.DataFrame({ "dock_id": [f"D{i:04d}" for i in range(1, n + 1)], "station": station, "age_months": age_months, "uses_per_week": uses_per_week, "model": model, "district": district, "fault_30d": fault_30d, }) docks.to_csv("docks.csv", index=False) print("Wrote docks.csv:", docks.shape[0], "rows,", docks.shape[1], "columns")Run it:
python make_rivermead.pyIt prints two lines:
Wrote demand.csv: 1460 rows, 6 columns Wrote docks.csv: 3000 rows, 7 columns -
Save this as
inspect_data.py:"""Load a bundled dataset and the two generated tables, and separate features from targets.""" import pandas as pd from sklearn.datasets import load_wine, make_classification wine = load_wine(as_frame=True) print("Wine features:", wine.data.shape, "| target counts:", wine.target.value_counts().sort_index().tolist()) print("Wine target names:", wine.target_names.tolist()) print("First feature columns:", wine.data.columns[:4].tolist()) X_made, y_made = make_classification(n_samples=500, n_features=6, n_informative=3, random_state=0) print("make_classification:", X_made.shape, "| positive share:", round(y_made.mean(), 3)) demand = pd.read_csv("demand.csv", parse_dates=["day"]) docks = pd.read_csv("docks.csv") print("Demand:", demand.shape, "| days", demand["day"].min().date(), "to", demand["day"].max().date()) print("Rentals: mean", round(demand["rentals"].mean(), 1), "| min", demand["rentals"].min(), "| max", demand["rentals"].max()) print("Docks:", docks.shape, "| missing uses_per_week:", int(docks["uses_per_week"].isna().sum())) print("Dock types:", docks.dtypes.astype(str).to_dict()) print("Fault share:", round(docks["fault_30d"].mean(), 3), "| districts:", sorted(docks["district"].unique())) X = docks.drop(columns=["dock_id", "fault_30d"]) y = docks["fault_30d"] print("Features:", X.columns.tolist(), "| target name:", y.name, "| rows:", len(y))Run it:
python inspect_data.pyOutput (every value should match):
Wine features: (178, 13) | target counts: [59, 71, 48] Wine target names: ['class_0', 'class_1', 'class_2'] First feature columns: ['alcohol', 'malic_acid', 'ash', 'alcalinity_of_ash'] make_classification: (500, 6) | positive share: 0.498 Demand: (1460, 6) | days 2022-01-01 to 2025-12-30 Rentals: mean 1443.8 | min 603 | max 2261 Docks: (3000, 7) | missing uses_per_week: 90 Dock types: {'dock_id': 'str', 'station': 'int64', 'age_months': 'int64', 'uses_per_week': 'float64', 'model': 'str', 'district': 'str', 'fault_30d': 'int64'} Fault share: 0.115 | districts: ['Castle', 'Harbour', 'Meadow', 'Station', 'University'] Features: ['station', 'age_months', 'uses_per_week', 'model', 'district'] | target name: fault_30d | rows: 3000
How the Generator Works
default_rng(2026) is the one source of randomness, created once at the
top. Every call on rng draws the next values from it, so the order of the
calls matters as much as the seed: swapping two lines would change the
tables. pd.date_range makes 1,460 consecutive days; season is a sine
wave over the day of the year, and temp_c adds noise to it with
rng.normal(0, 3, size=1460). rain_mm is zero on most days and a gamma
draw on the rest, using np.where to choose per day. weekend and promo
are 0-or-1 flags. rentals adds the effects together: 28 rentals per
degree, minus 9 per millimetre of rain, plus 180 on weekends, plus 240 on
promotion days, plus a slow growth of a quarter of a rental per day, plus
noise with spread 90. Rounding keeps the saved values tidy.
The docks block draws each column independently and then builds risk
from four of them. The line
1 / (1 + np.exp(-risk)) turns a risk score into a probability between 0
and 1, so that older, busier, model C and Harbour docks fail more often;
comparing a uniform draw with that probability decides each dock's fault.
Only after the target is fixed does the script blank out 90 usage values
with np.nan, so that the missing values are missing at random. station
is a group label the next lesson needs. Both tables are saved with
index=False so that the CSV has no extra numbering column.
How the Inspection Works
load_wine(as_frame=True) gives a DataFrame of 178 by 13 and a Series
with 59, 71 and 48 rows per class; the loader also names the classes and
the columns. make_classification returns arrays, not frames, with an
almost even split between the two classes.
pd.read_csv with parse_dates=["day"] reads the day column as dates, so
.min() and .max() are dates and .date() prints them without a time;
without the option the column would be text. The dtypes line shows pandas
3's str type for the text columns and float64 for the usage column,
because a column with missing values cannot be an integer column. The
fault share is 0.115: about one dock in nine fails, which makes this an
imbalanced target, and the classification module returns to what that
means. The last block is the separation every model needs: X is every
column except the identifier and the target, dropped with
drop(columns=...), and y is the target Series.
Success: the two generator lines report 1460 by 6 and 3000 by 7, the missing count is 90, and the fault share is 0.115.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
FileNotFoundError: [Errno 2] No such file or directory: 'demand.csv' | inspect_data.py was run from another folder, or the generator was not run | cd to the lesson folder and run python make_rivermead.py first |
AttributeError: 'str' object has no attribute 'date' | parse_dates missing, so the day column is text | Keep parse_dates=["day"] in read_csv |
| Different rentals or fault values with the same shapes | The seed or the order of the rng calls was changed | Restore default_rng(2026) and the line order; regenerate |
Dock types shows object instead of str | An older pandas | Check python check_setup.py from the setup lesson; the course uses pandas 3.0.6 |
Independent task: change the seed to default_rng(7), regenerate, and
rerun the inspection. Before you run it, write down which printed values
will change and which cannot. Restore 2026 and regenerate afterwards; every
later lesson expects the 2026 tables.
Reset: if an edit goes wrong, save the file again from this lesson and run it again. Any file a script writes is replaced when it runs again, so nothing needs removing first.
Cleanup: when you have finished the independent task, remove the lesson folder. macOS and Linux:
cd ~/sklearn-practice
ls
rm -rf load-bundled-and-generated-data
Windows PowerShell:
cd $HOME\sklearn-practice
ls
Remove-Item -Recurse load-bundled-and-generated-data
Check that ls lists load-bundled-and-generated-data before you remove it, and leave .venv
and requirements.txt in place for the next lesson.
Check Your Understanding
- Two learners run
make_classification(n_samples=500, n_features=6, n_informative=3, random_state=0)on different computers. Do they get the sameX? What if one of them leaves outrandom_state? - Why does
uses_per_weekprint asfloat64whileage_monthsprints asint64?
Answer and Reasoning
Independent task
With seed 7 the shapes, the column names, the date range and the missing count are unchanged: 1460 by 6, 3000 by 7, 90 missing. They do not depend on any random draw. Every drawn value changes, so the summaries move: rentals have mean 1440.0, minimum 625 and maximum 2308, and the fault share is 0.112. The districts list is the same because the five names are fixed and all appear. The generator with seed 2026 is the one the course's values come from, so restore it.
Understanding check
- Yes: with the same arguments, the same scikit-learn and the same
random_state, the generator draws the same values, which is why the lessons can print expected numbers. Withoutrandom_statethe seed is taken fresh each run, and the rows differ from run to run and from computer to computer. - The usage column has 90 missing values, written as
NaN, which is a floating-point value; an integer column has no way to hold a gap, so pandas stores the column asfloat64. The age column has no gaps and staysint64.