Dataset Loaders, Fetchers and Generators in scikit-learn
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
The sklearn.datasets package gives you data for learning, testing and benchmarking without writing any file-reading
code: small datasets that ship inside the wheel, helpers that download larger public datasets, generators that create
synthetic problems with a controlled structure, and a few readers for common file formats. This page explains the three
kinds of function, the Bunch object they return, where downloaded files are cached, how to load a dataset as a pandas
DataFrame, and what changed since the books and tutorials that still use load_boston or fetch_mldata. It targets
scikit-learn 1.9 (1.9.1 at the time of writing) with NumPy 2.5 and pandas 3.1, and was checked in
October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. Every example was run with Python 3.13, scikit-learn 1.9.1, NumPy 2.5.4 and pandas 3.1.0; the printed output
is the real output. Examples that download data need an internet connection the first time they run.
For reading your own CSV, Excel or Parquet files use pandas (see
Data Acquisition and Formats); sklearn.datasets is for the
reference datasets and for synthetic data.
Three kinds of function
The user guide groups the package into three families that share a naming convention:
| Family | What it does | Returns |
|---|---|---|
|
Reads a small standard dataset that is included in the scikit-learn installation. No network access. |
A |
|
Downloads a larger dataset the first time, stores it in a local cache and reads it from there afterwards. |
A |
|
Creates a synthetic dataset from a random number generator, with parameters for size, noise and structure. |
A tuple |
The Bunch object, return_X_y and as_frame
Loaders and fetchers return a Bunch: a dictionary whose keys are also attributes. It holds at least data (an array of
shape (n_samples, n_features); the 20 newsgroups text dataset is the exception) and target (the labels or values of
length n_samples), and usually feature_names, target_names and DESCR, a full description of the dataset.
from sklearn.datasets import load_iris
iris = load_iris()
print(type(iris).__name__, sorted(iris.keys()))
print(iris.data.shape, iris.target.shape, iris.feature_names)
print(iris.target_names, iris.DESCR[:60].replace("\n", " "))
print(iris["data"] is iris.data)
X, y = load_iris(return_X_y=True) # just the two arrays
print(type(X).__name__, X.shape, y[:5])
iris_df = load_iris(as_frame=True) # pandas objects, plus a combined frame
print(type(iris_df.frame).__name__, iris_df.frame.shape)
print(iris_df.frame.head(3))
print(type(iris_df.data).__name__, type(iris_df.target).__name__)
Output:
Bunch ['DESCR', 'data', 'data_module', 'feature_names', 'filename', 'frame', 'target', 'target_names'] (150, 4) (150,) ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] ['setosa' 'versicolor' 'virginica'] .. _iris_dataset: Iris plants dataset -------------------- True ndarray (150, 4) [0 0 0 0 0] DataFrame (150, 5) sepal length (cm) sepal width (cm) ... petal width (cm) target 0 5.1 3.5 ... 0.2 0 1 4.9 3.0 ... 0.2 0 2 4.7 3.2 ... 0.2 0 [3 rows x 5 columns] DataFrame Series
-
return_X_y=Truereturns(data, target)instead of aBunch, which is the idiom for a one-line load. -
as_frame=Truereturns pandas objects:databecomes a DataFrame,targeta Series (a DataFrame for several targets) and a combinedframeattribute appears. This needs pandas, and the column names come fromfeature_names. -
DESCRdescribes the origin, the meaning of every column and the licence or citation of the dataset. Print it before using the data. -
A
Bunchis not a DataFrame: there is no.head()on it, butbunch.frame.head()works whenas_frame=True.
Toy datasets
Six small datasets are bundled and need no download. They suit tutorials, unit tests and quick experiments, but their size makes them poor benchmarks.
from sklearn.datasets import load_breast_cancer, load_diabetes, load_digits, load_iris, load_linnerud, load_wine
for loader in (load_iris, load_diabetes, load_digits, load_wine, load_breast_cancer, load_linnerud):
b = loader()
print(f"{loader.__name__:20s} data={b.data.shape} target={b.target.shape}")
Output:
load_iris data=(150, 4) target=(150,) load_diabetes data=(442, 10) target=(442,) load_digits data=(1797, 64) target=(1797,) load_wine data=(178, 13) target=(178,) load_breast_cancer data=(569, 30) target=(569,) load_linnerud data=(20, 3) target=(20, 3)
| Loader | Task | Notes |
|---|---|---|
|
Classification, 3 classes |
Three iris species described by four measurements. The rows are sorted by class, so never split it without shuffling (see the pitfalls below). |
|
Regression |
Ten baseline variables (already centred and scaled) and a disease-progression measure for 442 patients. |
|
Classification, 10 classes |
8 by 8 greyscale images of handwritten digits, flattened to 64 features; |
|
Classification, 3 classes |
Chemical analysis of wines from three cultivars. |
|
Binary classification |
Features computed from digitised images of breast-mass cell nuclei. |
|
Multi-output regression |
Three exercise variables and three physiological variables for 20 people; the target has three columns. |
Real-world datasets and the data_home cache
Fetchers download a file on first use, then read it from a cache directory so later calls are offline. The directory is
~/scikit_learn_data by default; the SCIKIT_LEARN_DATA environment variable changes it, and the data_home argument of
every fetcher overrides it for one call. get_data_home() shows the current location and clear_data_home() deletes
the cache.
| Fetcher | Dataset |
|---|---|
|
Block-group housing data from the 1990 US census: 20640 rows, 8 numeric features and the median house value. The standard replacement for the Boston housing data. |
|
About 18000 newsgroup posts on 20 topics, as raw text or as a TF-IDF matrix; |
|
Face images for recognition and verification. |
|
Forest cover type from cartographic variables (several hundred thousand rows). |
|
Reuters newswire categories as a sparse multilabel problem. |
|
Network-intrusion records. |
|
Presence data for two South American species, for density-estimation examples. |
|
Any dataset from the openml.org repository, by name or numeric id. |
|
A single arbitrary file from a URL, with caching and an optional checksum. |
The next example fetches the California housing data into a throwaway cache directory (so nothing is written to your home directory), as a DataFrame and as arrays.
import tempfile
from sklearn.datasets import fetch_california_housing
cache = tempfile.mkdtemp()
cal = fetch_california_housing(data_home=cache, as_frame=True)
print(cal.frame.shape)
print(list(cal.frame.columns))
print(cal.frame.dtypes.unique())
X, y = fetch_california_housing(data_home=cache, return_X_y=True) # second call reads the cache
print(type(X).__name__, X.shape)
Output:
(20640, 9)
['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude', 'MedHouseVal']
[dtype('float64')]
ndarray (20640, 8)
The fetchers accept n_retries and delay to cope with flaky connections, and download_if_missing=False to fail
instead of downloading (useful in air-gapped CI). In a Docker image or CI job, point data_home at a persistent or
pre-populated directory so every run does not download again.
OpenML with fetch_openml
fetch_openml loads any of the thousands of datasets on openml.org. Select one by name (with a version) or by
data_id; target_column chooses the target ("default-target" uses the one the dataset declares); as_frame is
"auto" by default, which returns a pandas DataFrame for dense data and a sparse matrix for sparse data;
parser is "auto", "pandas" or "liac-arff"; cache=True stores the download in data_home.
import tempfile
from sklearn.datasets import fetch_openml
cache = tempfile.mkdtemp()
credit = fetch_openml("credit-g", version=1, data_home=cache, parser="auto")
print(type(credit.data).__name__, credit.data.shape, credit.target.name)
print("category columns:", credit.data.select_dtypes("category").shape[1], " numeric columns:", credit.data.select_dtypes("number").shape[1])
print(credit.target.value_counts().to_dict())
try:
credit.data[0] # the old array-style access
except KeyError as e:
print("KeyError", e)
arrays = fetch_openml("credit-g", version=1, data_home=cache, as_frame=False)
print(type(arrays.data).__name__, arrays.data.dtype, arrays.data[0][:4])
Output:
DataFrame (1000, 20) class
category columns: 13 numeric columns: 7
{'good': 700, 'bad': 300}
KeyError 0
ndarray object ['<0' 6 'critical/other existing credit' 'radio/tv']
The result is a DataFrame of 1000 rows and 20 columns, with 7 numeric columns and 13 columns in pandas category dtype,
and the target is a categorical Series named class. Things to know:
-
A DataFrame is the default. Older code such as
X = fetch_openml(...).data; X[0]indexed a NumPy array. Withas_frame="auto"the same code raisesKeyError, becauseX[0]looks up a column called0. UseX.iloc[0]or passas_frame=Falsefor the array behaviour; as the output shows, a dataset with categorical columns then comes back as an array of dtypeobjectholding strings and numbers, which most estimators cannot use directly (see ColumnTransformer & Heterogeneous Data). -
Pin the version. Without
version=, the default is"active", the version OpenML currently marks active, which can change; fixversion=. -
The service can be unavailable. During this check, a request returned HTTP 503 for the
adultdataset and the download of another dataset needed a retry. Cache the data, or keep a copy, for anything that must run unattended. -
Parser compatibility. With scikit-learn 1.9.1 and pandas 3.1.0,
fetch_openml("titanic", version=1)usingparser="pandas"(which"auto"selects for dense data) raisedTypeError: expected string or bytes-like object, got 'int'while building the DataFrame, andparser="liac-arff"returned the 1309 by 13 DataFrame. The 1.10 development release notes list a fix for this error (upcoming, not in 1.9.1). If you hit it, switch parser or choose another version of the dataset. -
Target and licence. OpenML datasets carry their own licence and description in
DESCR; read it.
Downloading one file is the job of fetch_file, which caches it in a folder and can verify a SHA-256 checksum, so a
changed or corrupted download fails loudly instead of silently feeding bad data into a model. The first call below
downloads and hashes the file; the later calls pass the checksum, and a wrong checksum raises OSError.
import hashlib
import tempfile
from pathlib import Path
import pandas as pd
from sklearn.datasets import fetch_file
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
folder = tempfile.mkdtemp()
path = Path(fetch_file(url, folder=folder)) # first call downloads
digest = hashlib.sha256(path.read_bytes()).hexdigest()
print(path.name, path.stat().st_size, "bytes")
path2 = fetch_file(url, folder=folder, sha256=digest) # later calls verify the checksum
print(Path(path2) == path, pd.read_csv(path2).shape)
try:
fetch_file(url, folder=tempfile.mkdtemp(), sha256="0" * 64)
except OSError as e:
print(type(e).__name__)
Output:
penguins.csv 13478 bytes True (344, 7) OSError
Removed loaders: load_boston and fetch_mldata
Two loaders that books from the 2010s rely on no longer exist.
| Old call | Status | Use instead |
|---|---|---|
|
Deprecated in 1.0 and removed in 1.2 |
|
|
The mldata.org service it used is gone, and the function no longer exists in 1.9 |
|
|
Those modules moved to |
|
Generated datasets
Generators create data with a known structure, which makes them the right tool for testing an algorithm’s behaviour,
teaching, and benchmarking scale (increase n_samples and n_features and watch the runtime). They return (X, y);
some take return_centers=True or coef=True to also return the ground truth.
| Generator | What it makes |
|---|---|
|
Multi-class problems with informative, redundant and noisy features, class imbalance ( |
|
Isotropic Gaussian clusters; |
|
Two interleaving half circles, or two concentric circles: non-linearly separable 2-D data. |
|
Classification benchmarks from the literature. |
|
A multilabel problem; returns a label indicator matrix. |
|
Linear regression with a chosen number of informative features and noise; |
|
Non-linear regression benchmarks. |
|
3-D manifolds for manifold-learning examples. |
|
Matrices and signals for decomposition and covariance estimation. |
|
Matrices with a bicluster structure. |
import numpy as np
from sklearn.datasets import (make_blobs, make_circles, make_classification, make_friedman1,
make_moons, make_multilabel_classification, make_regression,
make_s_curve, make_swiss_roll)
X, y = make_classification(n_samples=1000, n_features=20, n_informative=5, n_redundant=2,
n_classes=3, weights=[0.7, 0.2, 0.1], flip_y=0.01, class_sep=1.0, random_state=0)
print(X.shape, np.bincount(y))
X, y, coef = make_regression(n_samples=200, n_features=10, n_informative=3, noise=5.0, coef=True, random_state=0)
print(X.shape, y.shape, np.count_nonzero(coef))
X, y, centers = make_blobs(n_samples=[100, 50], centers=None, n_features=2, cluster_std=[1.0, 2.5], return_centers=True, random_state=0)
print(X.shape, centers.shape)
Xm, ym = make_moons(n_samples=300, noise=0.2, random_state=0)
print(Xm.shape, np.bincount(ym))
Xc, yc = make_circles(n_samples=300, factor=0.4, noise=0.05, random_state=0)
print(Xc.shape)
Xs, t = make_swiss_roll(n_samples=500, random_state=0)
print(Xs.shape, t.shape)
Xs, t = make_s_curve(n_samples=500, random_state=0)
print(Xs.shape)
X, y = make_friedman1(n_samples=100, n_features=10, noise=0.5, random_state=0)
print(X.shape)
X, Y = make_multilabel_classification(n_samples=50, n_classes=4, random_state=0)
print(X.shape, Y.shape)
Output:
(1000, 20) [694 202 104] (200, 10) (200,) 3 (150, 2) (2, 2) (300, 2) [150 150] (300, 2) (500, 3) (500,) (500, 3) (100, 10) (50, 20) (50, 4)
Notes on the output: with 3 classes and weights=[0.7, 0.2, 0.1] the class counts are close to, but not exactly, 700, 200
and 100, because flip_y=0.01 relabels about 1% of the samples at random. make_blobs with a list for n_samples
creates clusters of different sizes (100 and 50 here).
Reproducibility and random_state
Every generator takes random_state. An integer makes the data identical on every call and every machine with the same
versions; None draws from the global NumPy state and gives different data each time.
import numpy as np
from sklearn.datasets import make_moons
a = make_moons(50, noise=0.1, random_state=1)[0]
b = make_moons(50, noise=0.1, random_state=1)[0]
c = make_moons(50, noise=0.1)[0]
d = make_moons(50, noise=0.1)[0]
print(np.array_equal(a, b), np.array_equal(c, d))
try:
make_moons(10, random_state=np.random.default_rng(0))
except Exception as e:
print(type(e).__name__)
Output:
True False InvalidParameterError
Source: scikit-learn glossary: random_state.
Note the last case: in scikit-learn 1.9.1 the generators accept an integer, a numpy.random.RandomState or None, but
not a NumPy Generator created by np.random.default_rng, which the NumPy documentation recommends for new code.
The error message lists the accepted types. Pass an integer seed (or a RandomState) here.
Loading other data
| Function | Use |
|---|---|
|
The sparse text format used by libsvm, SVMlight and LIBLINEAR ( |
|
A directory with one sub-folder per class, each holding text files; returns a |
|
Two colour photographs bundled with scikit-learn, for image-processing examples (requires the Pillow package). |
|
One file from a URL, cached in a folder, with optional |
|
See above. |
import os
import tempfile
import numpy as np
from sklearn.datasets import dump_svmlight_file, load_files, load_sample_image, load_svmlight_file, make_classification
X, y = make_classification(20, 5, random_state=0)
workdir = tempfile.mkdtemp()
path = os.path.join(workdir, "toy.svmlight")
dump_svmlight_file(X, y, path, zero_based=True)
print(open(path).readline()[:70])
X2, y2 = load_svmlight_file(path)
print(type(X2).__name__, X2.shape, np.allclose(X2.toarray(), X, atol=1e-6))
for cls, docs in {"pos": ["good great", "nice"], "neg": ["bad awful"]}.items():
os.makedirs(os.path.join(workdir, "txt", cls))
for i, text in enumerate(docs):
with open(os.path.join(workdir, "txt", cls, f"{i}.txt"), "w") as f:
f.write(text)
bunch = load_files(os.path.join(workdir, "txt"), encoding="utf-8", shuffle=False)
print(sorted(bunch.keys()), bunch.target_names, bunch.target, bunch.data[0])
print(load_sample_image("china.jpg").shape, load_sample_image("china.jpg").dtype)
Output:
0 0:-0.1075610811978965 1:-0.904252075068515 2:-1.022285017717046 3:-0 csr_matrix (20, 5) True ['DESCR', 'data', 'filenames', 'target', 'target_names'] ['neg', 'pos'] [0 1 1] bad awful (427, 640, 3) uint8
Choosing and using datasets well
-
Toy datasets teach mechanics, not conclusions. A score on iris or digits says little about real projects. Use them to learn an API, write a test or illustrate a concept.
-
Sorted data.
load_irislists the 50 setosa rows first, then versicolor, then virginica. A split or a cross-validation without shuffling (train_test_split(..., shuffle=False), orKFoldwithoutshuffle=True) can put a whole class in one fold. The learning-curve example in Display Objects and Visualizations shows how it breaks. See Train/Test Split and Cross-Validation & Splitters. -
Synthetic data is easier than real data. Generators produce features that really are informative and noise that really is Gaussian. A model that succeeds on
make_classificationmay still fail on messy data; use generators to test an algorithm’s behaviour under conditions you control. -
Seed everything. Give every generator an integer
random_state, and see Reproducibility and MLOps Basics for the wider picture. -
Keep the cache out of the repository and out of the image layer you rebuild often: set
SCIKIT_LEARN_DATAordata_hometo a mounted or ignored directory. -
Read
DESCRand the licence. Real-world datasets come with citation and licence terms that apply to your use. -
Missing data. Some datasets contain missing values or categorical strings; plan the preprocessing with Imputing Missing Values and ColumnTransformer & Heterogeneous Data.