Sub topic 1
Features, Labels, and the scikit-learn Estimator API
Prerequisites
Assume basic Python, NumPy array shapes, pandas DataFrames, and the general idea of supervised learning.
Features and labels: what the model sees and what it predicts
In supervised learning, each example has features and usually a label. Features are the input measurements used by a model. The label is the target value the model learns to predict.
A feature matrix X contains input data. A label vector y contains the corresponding target for each row.
X row 0 ──> y[0]
X row 1 ──> y[1]
X row 2 ──> y[2]The shape of X and y
For tabular data, X normally has two dimensions:
- Rows represent samples, such as customers or flowers.
- Columns represent features, such as age or petal length.
y normally has one dimension, with one target per sample.
| Object | Typical shape | Meaning |
|---|---|---|
| `X` | `(n_samples, n_features)` | Input measurements |
| `y` | `(n_samples,)` | Target values |
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
print(X.shape) # (150, 4)
print(y.shape) # (150,)Classification and regression targets
Classification predicts categories. A target might be "spam" or "not spam", or an integer code such as 0, 1, or 2. The integer values represent classes, not quantities.
Regression predicts a numeric quantity. Examples include house price, temperature, and delivery time. Differences between values have meaning.
The target type affects the estimator you choose and how you evaluate its predictions. Accuracy is common for classification; mean squared error is common for regression.
Numeric and categorical features
A numeric feature contains quantities on which arithmetic is meaningful, such as income or height. A categorical feature contains named groups, such as city or subscription plan.
Many estimators require numeric input. Categorical values therefore need an encoding step, such as one-hot encoding, before modeling. Do not treat category codes as measurements unless their order and spacing are meaningful.
Holding out data with `train_test_split`
A test set is a held-out portion of data used to estimate performance on unseen examples. Split before fitting preprocessing or the model.
from sklearn.datasets import load_iris
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, X_test.shape)random_state makes the split repeatable. For classification, stratify=y helps preserve class proportions in both sets.
Exercise
What does y.shape == (n_samples,) tell you?
Show answer
There is one target value for each row in X.