This lab shows how to load and explore the datasets that ship with scikit-learn: the Breast Cancer Wisconsin classification set, a housing regression set and the 20 Newsgroups text corpus. The notebook embedded above was run on scikit-learn 0.20, and its load_boston call fails on current releases. The sections below explain what each step does, give updated code that runs on scikit-learn 1.x, and show how to inspect the data with pandas before you train a model.
What the notebook is doing
The sklearn.datasets module provides three kinds of data. Loaders (load_*) return small datasets that ship inside the package, so they work offline. Fetchers (fetch_*) download larger datasets the first time you call them and cache them under ~/scikit_learn_data. Generators (make_*) create synthetic data. The notebook above uses one loader (load_breast_cancer), one loader that has since been removed (load_boston) and one fetcher (fetch_20newsgroups).
Each loader and fetcher returns a Bunch. This is a dictionary whose keys can also be read as attributes, so ds['data'] and ds.data are the same thing. The keys you will use most often are listed below.
| Key | Contents |
|---|---|
data | Feature matrix of shape (n_samples, n_features), or a list of strings for text datasets |
target | Label or value to predict, one per sample |
feature_names | Column names for data |
target_names | Class names for classification sets. Index i names class i |
DESCR | Full description of the dataset: source, units, class distribution |
frame | A pandas DataFrame containing features and target. Only filled in when as_frame=True |
Note: Newer versions add keys such as frame and data_module, so keys() prints a longer list than the dict_keys([...]) output shown above. That is expected.
Set up a current environment
The output above comes from Python 3.7 with scikit-learn 0.20.2, numpy 1.16 and pandas 0.23. All of these are long out of support. Use a virtual environment with a currently supported Python 3 release:
python3 -m venv ~/venvs/sklearn-lab
source ~/venvs/sklearn-lab/bin/activate
pip install -U scikit-learn pandas jupyterlab
jupyter labCode language: JavaScript (javascript)
If you install from inside a notebook, use %pip rather than !pip. The %pip magic always installs into the environment of the running kernel. !pip runs whichever pip comes first on the shell PATH, and that is often a different Python.
%pip install -U scikit-learn pandas
import sklearn, numpy as np, scipy, pandas as pd
print("scikit-learn", sklearn.__version__)
print("numpy", np.__version__)
print("scipy", scipy.__version__)
print("pandas", pd.__version__)Code language: PHP (php)
Note: The PyPI package is called scikit-learn, but you import it as sklearn. Running pip install sklearn installs a deprecated placeholder package that fails on purpose.
Breast cancer dataset: the modern way
The example above builds two DataFrames by hand and joins them with pd.concat. That still works. Since scikit-learn 0.23, though, as_frame=True returns a ready-made DataFrame in .frame, and return_X_y=True returns just the features and target.
from sklearn.datasets import load_breast_cancer
bc = load_breast_cancer(as_frame=True)
df = bc.frame # 30 feature columns + 'target'
df = df.rename(columns={"target": "cancer"})
print(df.shape) # (569, 31)
# Or get X (DataFrame) and y (Series) directly
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
print(X.shape, y.shape) # (569, 30) (569,)Code language: PHP (php)
Pay attention to the label encoding. target_names is ['malignant', 'benign'], so 0 means malignant and 1 means benign. The first five rows in df.head() above all show cancer = 0, which means they are malignant tumours. A column called cancer can make readers assume 1 is the positive case. A clearer option is to add a readable label column:
df["diagnosis"] = df["cancer"].map(dict(enumerate(bc.target_names)))
print(df["diagnosis"].value_counts())
# benign 357
# malignant 212Code language: PHP (php)
Replacing the Boston housing dataset
load_boston was deprecated in scikit-learn 1.0 and removed in 1.2. On a current install, the import in the example above fails with ImportError: cannot import name 'load_boston'. The dataset was removed partly because its B feature encodes a racial proportion, as the DESCR output above shows, and the original paper's assumptions behind that variable have been criticised. scikit-learn recommends the California housing dataset as a regression alternative:
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True) # downloads once, then cached
print(housing.keys())
print(housing.feature_names)
# ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms',
# 'Population', 'AveOccup', 'Latitude', 'Longitude']
print(housing.data.shape) # (20640, 8)
print(housing.target.name) # MedHouseVal (median house value, in units of $100,000)
print(housing.frame.describe().T[["mean", "min", "max"]])Code language: PHP (php)
This is a fetcher, so the first call needs internet access. Every later call reads from the local cache. Like the Boston set, it is a regression problem: the target is a continuous number, not a class. This is why it has no target_names key.
Loading the 20 Newsgroups text dataset
The notebook ends just as it imports fetch_20newsgroups. This dataset contains about 18,000 newsgroup posts across 20 topics, already split into train and test subsets. The data key holds a list of raw strings, not a numeric matrix, so you have to vectorise the text before any estimator can use it.
from sklearn.datasets import fetch_20newsgroups
train = fetch_20newsgroups(
subset="train", # 'train', 'test' or 'all'
remove=("headers", "footers", "quotes"), # strip metadata the model could cheat on
random_state=42,
)
print(len(train.data)) # number of documents (11314 for 'train')
print(len(train.target_names)) # 20
print(train.target_names[:5])
print(train.data[0][:300]) # first 300 characters of the first post
# Load only a few categories for faster experiments
subset = fetch_20newsgroups(subset="train",
categories=["sci.space", "rec.autos"])
print(subset.target_names, len(subset.data))Code language: PHP (php)
Removing headers, footers and quotes matters. Without it, a classifier can learn from email addresses and signatures rather than the content. That gives you scores that look good but will not hold up on new text.
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(max_features=20000, stop_words="english")
X_text = vec.fit_transform(train.data)
print(X_text.shape) # (n_documents, 20000) sparse matrixCode language: PHP (php)
A quick exploration checklist
Shape and keys are only the start. Before you train on any tabular dataset, run these checks on its DataFrame:
df.info() # dtypes and non-null counts
print(df.isna().sum().sum()) # total missing values (0 here)
print(df.describe().T.head(10)) # ranges: note very different scales
print(df["cancer"].value_counts(normalize=True)) # class balance
print(df.corr(numeric_only=True)["cancer"].sort_values().head(5))Code language: PHP (php)
- Scale differences:
mean arearuns into the thousands whilemean smoothnessstays below 1. Distance-based and gradient-based models such as KNN, SVM and logistic regression need feature scaling. - Class balance: roughly 63% benign and 37% malignant. Use a stratified split so the train and test sets keep the same ratio.
- Correlated features: radius, perimeter and area measure almost the same thing. This matters if you interpret linear model coefficients.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
ImportError: cannot import name 'load_boston' | Removed in scikit-learn 1.2 | Use fetch_california_housing or another regression dataset |
ModuleNotFoundError: No module named 'sklearn' | Package installed into a different environment | Run %pip install scikit-learn in the notebook and restart the kernel |
URLError or HTTP error on fetch_* | No internet access, or a proxy or firewall blocks the download | Download on a connected machine and copy the ~/scikit_learn_data folder across, or pass data_home= to point at a shared cache |
TypeError: __init__() got an unexpected keyword argument 'as_frame' | Very old scikit-learn | Upgrade to a current 1.x release |
df.corr() raises on string columns | Newer pandas no longer drops non-numeric columns silently | Pass numeric_only=True or drop the label column first |
Next step: a first baseline model
After exploring the data, a short pipeline confirms it is ready for modelling. It also shows why scaling and stratification matter:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test),
target_names=["malignant", "benign"]))Code language: JavaScript (javascript)
Note: Fit the scaler inside the pipeline on the training data only. If you scale the whole dataset before splitting, test-set statistics leak into training and the scores come out optimistic.
Frequently asked questions
Why does load_boston not work in scikit-learn?
It was deprecated in version 1.0 and removed in 1.2, partly because of ethical problems with one of its features. Use fetch_california_housing for a comparable regression exercise.
In load_breast_cancer, does target 1 mean malignant?
No. target_names is ['malignant', 'benign'], so 0 is malignant and 1 is benign. The dataset contains 212 malignant and 357 benign samples.
Where does scikit-learn store downloaded datasets?
By default in ~/scikit_learn_data. You can change this with the data_home argument or the SCIKIT_LEARN_DATA environment variable.
How do I get a scikit-learn dataset as a pandas DataFrame?
Pass as_frame=True to the loader and read .frame. To get a features DataFrame and a target Series directly, add return_X_y=True.
What is the difference between load_ and fetch_ functions?
load_* functions read small datasets bundled with the package and work offline. fetch_* functions download larger datasets on first use and cache them locally.
Related tutorials
- More Machine Learning tutorials
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals