Sub topic 2
The shape of X and y
This chapter assumes you know basic Python, NumPy arrays and their shapes, and what supervised learning is. It covers the shapes scikit-learn expects for the feature matrix X and the label vector y, and the errors you get when they are wrong.
The convention
scikit-learn expects X to be a 2D array with shape (n_samples, n_features). Each row is one sample and each column is one feature. It expects y to be a 1D array with shape (n_samples,), holding one label per sample.
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
print(X.shape) # (150, 4)
print(y.shape) # (150,)The iris data has 150 flowers and 4 measurements for each one. The first axis of X and the only axis of y must have the same length. Every estimator checks this, and a mismatch raises a ValueError.
Common shape errors
Two mistakes account for most shape errors.
- A single feature stored as a 1D array. A 1D array has no column axis, so scikit-learn cannot tell whether it is one sample with many features or many samples with one feature.
- A column-vector
y. Aywith shape(n, 1)triggers aDataConversionWarning. Most estimators still run, but they convert it for you.
The first mistake looks like this.
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.array([1.0, 2.0, 3.0, 4.0])
y = np.array([2.0, 4.0, 6.0, 8.0])
model = LinearRegression()
try:
model.fit(x, y)
except ValueError as err:
print("Error:", str(err).splitlines()[0])
model.fit(x.reshape(-1, 1), y)
print(model.predict([[5.0]]))The call x.reshape(-1, 1) turns the 4 values into 4 rows of 1 column. The -1 tells NumPy to work out that length itself. The same applies when you predict: predict needs a 2D input, so a single sample must be wrapped as [[5.0]], not [5.0].
For a column-vector y, use y.ravel() to flatten it to 1D.
Shapes with pandas
A DataFrame is already 2D, so it works directly as X. Selecting one column with single brackets gives a Series, which is 1D. Selecting it with double brackets gives a one-column DataFrame, which is 2D.
import pandas as pd
df = pd.DataFrame({
"age": [22, 35, 47],
"income": [30, 52, 61],
"bought": [0, 1, 1],
})
X = df[["age", "income"]] # DataFrame, shape (3, 2)
y = df["bought"] # Series, shape (3,)
x_one = df[["age"]] # DataFrame, shape (3, 1)
print(X.shape, y.shape, x_one.shape)Summary of expected shapes
| Object | Expected shape | Example |
|---|---|---|
| `X` | `(n_samples, n_features)` | `(150, 4)` |
| `y` | `(n_samples,)` | `(150,)` |
| Input to `predict` | `(m_samples, n_features)` | `(1, 4)` |
| Output of `predict` | `(m_samples,)` | `(1,)` |
The number of features at prediction time must match the number used in fit. Only the number of rows can change.
Exercise
You have a list of 6 house sizes, sizes = [50, 60, 75, 80, 95, 110], and a list of 6 prices. You convert them with X = np.array(sizes) and call model.fit(X, prices), which raises a ValueError. What is the shape of X, what should it be, and how do you fix it?
Show answer
The shape of X is (6,), which is 1D. It should be (6, 1), with 6 samples and 1 feature. Fix it with X = np.array(sizes).reshape(-1, 1). The prediction input must also be 2D, for example model.predict([[70]]).