Sub topic 2
The shape of X and y
This chapter covers the array shapes scikit-learn expects for features and labels, and the errors you get when the shapes are wrong. It assumes you know basic Python, NumPy arrays and their .shape attribute, and pandas DataFrames. It also assumes you know what supervised learning is. The previous chapter explained what features and labels are. This one is about how they are laid out in memory and how to check that layout.
The convention: rows are samples, columns are features
Every scikit-learn estimator that learns from labeled data expects two inputs:
X, the feature matrix. It is a 2D structure with shape(n_samples, n_features). Each row is one example, and each column is one measured property.y, the label vector. It is a 1D structure with shape(n_samples,). Entryiis the label for rowiofX.
The only hard rule linking them is that X.shape[0] == y.shape[0]. Row i of X and entry i of y must describe the same sample.
The built-in iris loader returns data in exactly this layout:
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
print(X.shape) # (150, 4)
print(y.shape) # (150,)There are 150 flowers and 4 measurements per flower, so X has 150 rows and 4 columns. The labels y form a flat array of 150 integers.
Why X is capitalized and y is not
The naming follows a mathematical convention. A capital letter denotes a matrix, and a lowercase letter denotes a vector. You will see this in all scikit-learn documentation. Following it makes your code easy for others to read, but nothing enforces it.
Samples versus features: which axis is which
A frequent source of confusion is that a table can be oriented either way. In scikit-learn the sample axis is always axis 0. If your data arrives with one column per sample, for example from a spreadsheet exported with measurements as rows, transpose it first with X.T.
A quick sanity check is to compare the shape against what you expect. If you have 150 flowers and 4 measurements, (150, 4) is right and (4, 150) is wrong. The estimator cannot detect this on its own. It would treat your 4 samples as having 150 features each, and the model would silently learn something meaningless or fail later.
What counts as a valid X
X does not have to be a NumPy array. Estimators accept anything that can be converted to a 2D numeric array:
- A NumPy
ndarray. - A pandas
DataFrame. - A nested list such as
[[1.0, 2.0], [3.0, 4.0]]. - A SciPy sparse matrix, which many estimators accept to save memory when most entries are zero.
Under the hood, most estimators call a validation helper that converts the input to an array and checks its dimensions. After conversion, the shape rules are the same whatever the input type.
A DataFrame has one extra feature. If X is a DataFrame, the estimator records the column names during fit. This lets scikit-learn warn you later if you pass data with different column names to predict.
import pandas as pd
from sklearn.linear_model import LinearRegression
df = pd.DataFrame({
"rooms": [2, 3, 4, 5],
"area": [40.0, 65.0, 80.0, 110.0],
"price": [150.0, 210.0, 260.0, 340.0],
})
X = df[["rooms", "area"]] # double brackets: a DataFrame with 2 columns
y = df["price"] # single brackets: a Series
print(X.shape) # (4, 2)
print(y.shape) # (4,)
model = LinearRegression().fit(X, y)
print(model.feature_names_in_) # ['rooms' 'area']
print(model.n_features_in_) # 2The difference between df[["rooms", "area"]] and df["price"] matters. Double brackets select a list of columns and return a 2D DataFrame. Single brackets select one column and return a 1D Series.
The most common error: a 1D X
Suppose you have one feature, such as area, and you select it with single brackets. You get a 1D object, and scikit-learn raises an error:
import numpy as np
from sklearn.linear_model import LinearRegression
area = np.array([40.0, 65.0, 80.0, 110.0]) # shape (4,)
price = np.array([150.0, 210.0, 260.0, 340.0])
try:
LinearRegression().fit(area, price)
except ValueError as err:
print(err)The message says that a 2D array was expected and a 1D array was given. It suggests reshaping with reshape(-1, 1) if the data has a single feature, or reshape(1, -1) if it has a single sample.
A single feature still needs a column axis, because the estimator needs to know how many features there are. The fix for one feature is:
import numpy as np
from sklearn.linear_model import LinearRegression
area = np.array([40.0, 65.0, 80.0, 110.0])
price = np.array([150.0, 210.0, 260.0, 340.0])
X = area.reshape(-1, 1) # shape (4, 1)
model = LinearRegression().fit(X, price)
print(X.shape) # (4, 1)
print(model.predict([[90.0]]))In reshape(-1, 1), the -1 means "work out this dimension from the rest". Four values in one column gives 4 rows.
The same rule applies when you predict. To predict for a single new sample with 2 features, pass shape (1, 2), which is [[3, 70.0]]. Passing [3, 70.0] is read as a 1D array and raises the same error.
Shape of y: 1D, with one exception
For most tasks y is 1D with shape (n_samples,). A column vector of shape (n_samples, 1) is a common mistake. Many classifiers accept it but emit a DataConversionWarning saying they expected a 1D array and will flatten it. The result is usually still correct, but you should fix it at the source with y.ravel() or by selecting a Series from the DataFrame.
The exception is multi-output prediction, where one sample has several targets. In that case y has shape (n_samples, n_targets), and the estimator predicts a 2D result.
| Situation | Shape of `y` |
|---|---|
| One target per sample (the usual case) | `(n_samples,)` |
| Several targets per sample (multi-output) | `(n_samples, n_targets)` |
| Column vector by accident | `(n_samples, 1)`, flatten with `ravel()` |
Unsupervised estimators, such as KMeans or PCA, do not use labels. Their fit method takes only X. In a pipeline, fit(X, y=None) is still the uniform signature so that all steps can be called the same way.
Mismatched lengths
If X and y have a different number of rows, fit raises a ValueError that reports the inconsistent numbers of samples. This often happens after filtering rows from one but not the other. For instance, you may drop rows with missing values from X and forget to drop the matching labels.
import numpy as np
from sklearn.linear_model import LogisticRegression
X = np.array([[0.0], [1.0], [2.0], [3.0]])
y = np.array([0, 0, 1]) # one label too few
try:
LogisticRegression().fit(X, y)
except ValueError as err:
print(err)Filtering both together avoids the problem. Build one boolean mask and apply it to both objects.
Shapes after splitting and predicting
The output shapes follow directly from the input shapes. After train_test_split, the training pair has matching row counts, and so does the test pair. Predictions have one entry per row of the input.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
print(X_train.shape, y_train.shape) # (112, 4) (112,)
print(X_test.shape, y_test.shape) # (38, 4) (38,)
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
print(model.predict(X_test).shape) # (38,)
print(model.predict_proba(X_test).shape) # (38, 3)
print(model.coef_.shape) # (3, 4)Three shapes are worth learning here:
predictreturns(n_samples,), one label per row.predict_probareturns(n_samples, n_classes), one probability per class per row.coef_returns(n_classes, n_features)for this multiclass model, so each class has one weight per feature.
The number of columns in any X you pass to predict must equal the number of columns seen in fit. The estimator stores that count as n_features_in_. If you pass a different number, you get a ValueError. Common causes are dropping a column from the test set only, or one-hot encoding the training and test sets separately so they end up with different column counts. Fitting a single preprocessing step on the training data, as covered in later chapters, prevents this.
A checklist before calling fit
Print the shapes and compare them against what you expect:
X.ndim == 2. If not, reshape a single feature withreshape(-1, 1).y.ndim == 1for single-target tasks. If not, flatten it.X.shape[0] == y.shape[0].X.shape[1]equals the number of features you intended, and the same count will be supplied at prediction time.
Exercise
You have a pandas DataFrame df with columns "temp", "humidity", and "rain". You want to predict "rain" from "temp" alone using LinearRegression. Write the lines that build X and y, give their shapes for a 100-row DataFrame, and explain why df["temp"] would fail as X.
Show answer
Use X = df[["temp"]] and y = df["rain"]. X has shape (100, 1) and y has shape (100,). df["temp"] returns a 1D Series of shape (100,), so fit raises a ValueError saying a 2D array was expected. The double brackets keep a column axis, which scikit-learn needs even for a single feature.
Exercise
A trained classifier was fit on X_train with shape (112, 4) and 3 classes. What shapes do predict and predict_proba return for a test array of shape (38, 4)? What happens if you pass shape (38, 3)?
Show answer
predict returns (38,) and predict_proba returns (38, 3). Passing (38, 3) raises a ValueError because the model was fit with 4 features (n_features_in_ == 4) and the input has 3.