Machine Learning with Scikit-learn / Data and Splits

Load bundled and generated data

Lesson 5 of 37. Open to read. No account needed.

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

LoaderRows by columnsTaskTarget
load_iris150 by 4classification3 species
load_wine178 by 13classification3 cultivars
load_breast_cancer569 by 30classification2 classes
load_diabetes442 by 10regressiondisease progression
load_digits1,797 by 64classification10 digits
load_linnerud20 by 3regression3 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_regression does 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_blobs draws points around chosen centres, and make_moons draws 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.

  1. Create the lesson folder. macOS and Linux:

    mkdir -p ~/sklearn-practice/load-bundled-and-generated-data
    cd ~/sklearn-practice/load-bundled-and-generated-data
    

    Windows PowerShell:

    mkdir $HOME\sklearn-practice\load-bundled-and-generated-data
    cd $HOME\sklearn-practice\load-bundled-and-generated-data
    
  2. 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.py
    

    It prints two lines:

    Wrote demand.csv: 1460 rows, 6 columns
    Wrote docks.csv: 3000 rows, 7 columns
    
  3. 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.py
    

    Output (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 seeLikely causeNext step
FileNotFoundError: [Errno 2] No such file or directory: 'demand.csv'inspect_data.py was run from another folder, or the generator was not runcd 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 textKeep parse_dates=["day"] in read_csv
Different rentals or fault values with the same shapesThe seed or the order of the rng calls was changedRestore default_rng(2026) and the line order; regenerate
Dock types shows object instead of strAn older pandasCheck 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

  1. Two learners run make_classification(n_samples=500, n_features=6, n_informative=3, random_state=0) on different computers. Do they get the same X? What if one of them leaves out random_state?
  2. Why does uses_per_week print as float64 while age_months prints as int64?

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

  1. 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. Without random_state the seed is taken fresh each run, and the rows differ from run to run and from computer to computer.
  2. 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 as float64. The age column has no gaps and stays int64.

References

32 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy