Sub topic 1
Features and labels: what the model sees and what it predicts
Prerequisites
This chapter assumes you know the following:
- Basic Python, including classes and methods.
- Basic NumPy arrays and how to read their shapes.
- Enough pandas to select columns from a DataFrame.
- The general idea of supervised learning: a model learns from examples that already have answers.
You do not need to know any scikit-learn yet. This chapter sets up the vocabulary that every later chapter uses.
Why this split matters
Almost every supervised learning workflow in scikit-learn begins by dividing a table into two parts. One part is what the model is allowed to look at. The other part is what you want it to predict. Every estimator in the library expects these two parts to be passed separately, so getting the split right is the first step of every project.
- Features are the input values that describe one example. A feature is a single measurable property, such as a person's age or the length of a flower petal. Features are also called predictors, inputs, or independent variables.
- A label is the answer you want the model to produce for one example. Labels are also called targets, outputs, or the dependent variable.
- A sample is one example. In a table, a sample is one row.
scikit-learn uses a fixed naming convention for these parts, and you will see it in nearly all code and documentation:
| Name | Meaning | Typical type |
|---|---|---|
| `X` | The feature matrix, one row per sample and one column per feature | 2D array or DataFrame |
| `y` | The label vector, one value per sample | 1D array or Series |
The capital X and lowercase y follow a mathematical habit: a matrix gets a capital letter and a vector gets a lowercase one. The convention is useful because it reminds you of the expected dimensions.
The learning setup
During training, the model sees both X and y. It looks for a relationship between them. During prediction, it sees only X for new samples and returns its guess for y.
This is why labels must never appear inside X. If a column of X already contains the answer, or something derived from it, the model can look good on your data and fail on real inputs, where the answer is not available. Chapter material on data leakage covers this in more detail. For now, remember the rule: X holds only information you would have at prediction time.
Loading a ready-made example
scikit-learn ships small datasets for practice. Many of the loaders accept return_X_y=True, which returns the two parts directly instead of a bundle object.
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 dataset describes 150 flowers. Each flower has four measurements (sepal length, sepal width, petal length, petal width), so X has 150 rows and 4 columns. The label for each flower is its species, stored as the integers 0, 1, and 2. Because there is one label per flower, y has 150 entries and a single dimension.
The next chapter looks at these shapes in detail. The one thing to check now is that the first dimension of X and the length of y match. Each row of X must line up with the label at the same position in y. If you shuffle or filter one without the other, the pairs break and the model learns from wrong answers without raising any error.
Splitting a DataFrame into X and y
Real data usually starts as a pandas DataFrame with the label in one of its columns. You separate them by selecting columns.
import pandas as pd
df = pd.DataFrame({
"age": [22, 35, 47, 52],
"city": ["Paris", "Rome", "Paris", "Oslo"],
"bought": [0, 1, 1, 0],
})
X = df[["age", "city"]] # double brackets: a DataFrame, 2D
y = df["bought"] # single brackets: a Series, 1D
print(X.shape) # (4, 2)
print(y.shape) # (4,)The brackets matter. df[["age", "city"]] passes a list of column names and returns a two-dimensional DataFrame. df["bought"] passes one name and returns a one-dimensional Series. If you wrote df[["bought"]] for the label, you would get a DataFrame with shape (4, 1). Many estimators accept that but emit a warning about the shape, and some produce output of an unexpected shape.
A safer way to build X when the label is a known column is to drop it:
X = df.drop(columns="bought")
y = df["bought"]This keeps X correct if you later add a new feature column, because you do not need to update a list of names.
What counts as a feature
A feature is any column the model is allowed to use. Choosing features is a modeling decision, and these cases come up often.
- Identifiers. A customer ID or row number rarely carries meaning. If IDs were assigned in order, they may still correlate with time or with the label by accident. Usually you leave them out of
X. - Columns derived from the label. A column such as "refund issued" in a model that predicts "customer unhappy" may be set only after the outcome is known. Leave it out.
- Columns unavailable at prediction time. If a value is recorded only after the event you are predicting, you cannot supply it when the model runs in production.
- Constant columns. A column with the same value in every row adds nothing. It is harmless but wasteful.
Feature matrices in other forms
The shapes above describe a dense table, which is the most common case. scikit-learn also accepts other containers for X:
- A NumPy array of shape
(n_samples, n_features). - A pandas DataFrame with the same row and column structure.
- A SciPy sparse matrix, useful when most values are zero, such as word counts in text.
- A nested Python list, which scikit-learn converts to an array internally.
When you pass a DataFrame, many estimators remember the column names in an attribute called feature_names_in_. They then warn you if you later pass data whose columns differ in name or order. That check catches a common mistake: training on columns in one order and predicting with another.
Checking your setup
Before fitting anything, it helps to run a few quick checks on X and y. They take seconds and prevent confusing errors later.
import numpy as np
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
assert X.ndim == 2, "X must be 2D"
assert y.ndim == 1, "y must be 1D"
assert X.shape[0] == y.shape[0], "X and y need the same number of rows"
print("features:", X.shape[1])
print("samples:", X.shape[0])
print("classes:", np.unique(y))Each assertion maps to one of the common errors you will see from scikit-learn:
| Symptom | Likely cause |
|---|---|
| `Expected 2D array, got 1D array instead` | You passed a single column as a flat array. Reshape it with `X.reshape(-1, 1)`, or select it with double brackets in pandas. |
| `Found input variables with inconsistent numbers of samples` | `X` and `y` have different lengths, often after filtering only one of them. |
| A shape warning about `y` having shape `(n, 1)` | The label was selected as a DataFrame instead of a Series. |
Putting it together
The vocabulary for the rest of this tutorial is now in place.
- A sample is one row. A feature is one column of
X. Xis two-dimensional with one row per sample.yis one-dimensional with one label per sample.- The model learns from
Xandytogether and predictsyfromXalone. Xmust contain only information available at prediction time.
Exercise
A DataFrame df has columns sqft, rooms, year_built, and price. You want to predict price. Write the two lines that build X and y. Then state the shapes if df has 500 rows.
Show answer
X = df.drop(columns="price") and y = df["price"]. X has shape (500, 3) and y has shape (500,). Using df[["price"]] for y would give (500, 1), which is the wrong shape for a label vector.
Exercise
A model predicting whether a loan will default has a column collections_started in X. It is set to true only after a borrower misses several payments. Should it stay in X? Explain.
Show answer
No. The value is known only after the outcome you are predicting is already happening, so it will not be available when a new application arrives. Keeping it would leak the answer into X, and the model would score well on historical data and poorly on real applications.