Sub topic 3
Examples, features, and labels
This chapter assumes you can write basic Python, read a table of numbers as rows and columns, and use NumPy arrays. Every later chapter relies on the vocabulary introduced here. Most beginner errors in machine learning come from mixing up these terms, or from putting the wrong columns into the wrong place.
The three words
A dataset for machine learning is usually a table. Each piece of that table has a name.
- An example (also called a sample, instance, or row) is one item the model learns from or predicts for. One flower, one email, one house sale, or one customer is one example.
- A feature (also called an input, attribute, predictor, or column) is a measurable property of an example. Petal length is a feature of a flower. Square footage is a feature of a house.
- A label (also called a target or output) is the answer you want the model to predict for an example. The species of a flower and the sale price of a house are labels.
Here is a small table of house sales.
| Example | Area (m²) | Bedrooms | Has garden | Sale price (label) |
|---|---|---|---|---|
| 1 | 70 | 2 | no | 210000 |
| 2 | 120 | 4 | yes | 390000 |
| 3 | 95 | 3 | yes | 295000 |
Each row is an example. The first three columns are features. The last column is the label. A model trained on this table learns a relationship between the features and the label, so it can estimate a price for a house whose price is not yet known.
Features and labels as arrays
Libraries such as scikit-learn expect the data as two separate objects, by convention named X and y.
Xis the feature matrix. It has one row per example and one column per feature, so its shape is(n_examples, n_features).yis the label vector. It has one entry per example, so its shape is(n_examples,).
The capital letter for X and lowercase for y is a convention from mathematics: a matrix is capital, a vector is lowercase. The row order must match. Row i of X and entry i of y describe the same example.
The following code loads the iris dataset and inspects these pieces.
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
print(X.shape) # (150, 4): 150 examples, 4 features
print(y.shape) # (150,): one label per example
print(iris.feature_names) # the four column names
print(iris.target_names) # the three class names
print(X[0], y[0]) # the first example and its labelThe dataset has 150 examples. Each example has four features: sepal length, sepal width, petal length, and petal width, all in centimeters. The label is a number 0, 1, or 2, and target_names maps each number to a species name.
Kinds of features
Features come in different types, and the type decides how you prepare them. Models work with numbers, so non-numeric features must be converted.
| Feature type | Example | Typical preparation |
|---|---|---|
| Numeric, continuous | Height in cm, temperature | Often scaled to a similar range |
| Numeric, discrete | Number of bedrooms | Used as is, or scaled |
| Binary | Has garden: yes or no | Encode as 0 and 1 |
| Categorical, unordered | Color: red, green, blue | One-hot encoding |
| Categorical, ordered | Size: small, medium, large | Ordinal encoding, which keeps the order |
| Text, image, audio | An email body | Convert to numbers first, for example word counts |
Encoding a categorical feature
Suppose a feature holds the neighborhood of a house. If you replace the names with 0, 1, and 2, the model will treat neighborhood 2 as "twice" neighborhood 1, which is meaningless for names. One-hot encoding avoids this by creating one 0/1 column per category.
import pandas as pd
df = pd.DataFrame(
{
"area": [70, 120, 95],
"neighborhood": ["north", "south", "north"],
"price": [210000, 390000, 295000],
}
)
X = pd.get_dummies(df[["area", "neighborhood"]], columns=["neighborhood"], dtype=int)
y = df["price"]
print(X)
print(y.tolist())The output has the columns area, neighborhood_north, and neighborhood_south. Notice that the label column price is not part of X. It was selected separately into y.
Labels: what the answer looks like
The label's form determines the kind of supervised task, which the next chapters cover in detail.
- If the label is a category, such as a species or "spam" versus "not spam", the task is classification.
- If the label is a number on a continuous scale, such as a price or a temperature, the task is regression.
- If there is no label at all, the task is unsupervised, and the model looks for structure in the features alone.
Class labels are often stored as integers, as in iris. The integers are names, not quantities. Class 2 is not "more" than class 0.
Where do labels come from? They are rarely free. Common sources are:
- Human annotation, such as people tagging images or marking emails as spam.
- Recorded outcomes, such as whether a customer later canceled a subscription, or the price a house actually sold for.
- Measurements from instruments, such as lab results.
Labeling cost is one of the main practical reasons to choose an unsupervised method, a point the chapter on choosing a paradigm returns to.
Why the feature and label split matters
The split defines the problem you are solving. The same table can produce different problems depending on which column you call the label. In the house table, using price as the label gives a regression problem. Using "has garden" as the label gives a classification problem, and price becomes one of the features.
Feature selection and feature quality
A model can only use the information that the features contain. If sale price depends mainly on location and you do not include any location feature, no model will recover that information. Adding informative features often helps more than switching to a fancier algorithm.
Irrelevant features can hurt as well. They add noise, and with few examples a model may latch onto accidental patterns. A useful rule is to include features you have a reason to believe relate to the label, and then check on held-out data whether they help.
Feature scaling
Features often have very different ranges. Area might be in the hundreds while bedrooms are between 1 and 6. Some models, such as k-nearest neighbors and models trained with gradient descent, behave badly when one feature has a much larger range than the others. Other models, such as decision trees, are not affected.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[70.0, 2], [120.0, 4], [95.0, 3]])
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
print(X_scaled.mean(axis=0)) # approximately [0, 0]
print(X_scaled.std(axis=0)) # [1, 1]StandardScaler subtracts each column's mean and divides by its standard deviation. In a real project, fit the scaler on the training data only, then apply it to the test data. Fitting on all the data lets information about the test set leak into training.
Common mistakes
Label leakage
Leakage happens when a feature contains information that would not be available at prediction time, or that is a disguised copy of the label. Suppose you predict whether a patient has a disease and one feature is "received treatment for the disease". The model will score very well in testing and fail in real use, because that feature is only known after the diagnosis.
To check for leakage, ask for every feature: "Would I know this value at the moment I need to make the prediction?" Be suspicious of any feature that gives surprisingly perfect accuracy.
Row order mismatch
If you sort or shuffle X without applying the same change to y, labels no longer match their examples. Use functions that shuffle both together, such as train_test_split, or keep the features and label in one DataFrame until the final split.
Treating identifiers as features
A column such as customer ID or row number looks like a number but carries no meaning. A model may use it to memorize examples. Drop identifiers unless they truly encode information, such as a timestamp-like sequence number.
Missing values
Real tables have gaps. Most scikit-learn models raise an error on NaN. You can drop rows, drop columns, or fill gaps with a value such as the column median.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[70.0, 2], [np.nan, 4], [95.0, 3]])
imputer = SimpleImputer(strategy="median")
print(imputer.fit_transform(X))Here the missing area is replaced by the median of the other two areas, which is 82.5.
Putting it together
A typical first step with any new table follows the same path.
- Decide what you want to predict. That column becomes the label
y, or you decide there is none. - Choose the columns that will be features and remove identifiers and anything that leaks the label.
- Convert non-numeric features to numbers.
- Handle missing values.
- Check the shapes:
Xis(n_examples, n_features),yis(n_examples,), and the lengths match.
Exercise
A table has columns customerid, age, monthlyspend, dayssincelast_login, and canceled (yes or no, recorded 30 days after the other columns). You want to predict whether a customer will cancel. Name the label, list the features you would keep, say which column you would drop and why, and say whether the task is classification or regression.
Show answer
The label is canceled. Keep age, monthlyspend, and dayssincelastlogin as features. Drop customer_id, because it is an identifier with no meaning that a model could generalize from, and it invites memorization. The task is classification, because the label is a category with two values (yes or no).
Exercise
You load a dataset into X with 500 rows and 8 columns, and y with 500 entries. After one-hot encoding a categorical column that had 5 categories (and removing the original column), what is the shape of X?
Show answer
X has shape (500, 12). The original column is replaced by 5 new columns, so the feature count changes from 8 to 8 - 1 + 5 = 12. The number of examples stays 500, and y is unchanged with shape (500,).