Features and Labels: How Data Is Shaped for ML
Before any learning happens, data has to be arranged the way algorithms expect. The vocabulary is short and used everywhere, from textbooks to library documentation.
Samples, features and labels
- A sample (or example, or row) is one thing you want to make a prediction about: one email, one house, one fruit.
- Features are the measured inputs that describe a sample: the house's floor area, number of bedrooms and neighborhood. In code, the features of all samples are often called
X. - The label, also called the target, is the answer you want to predict: the sale price, or "spam". The labels are often called
y.
Training a supervised model means finding a function that maps X to y. The model only ever sees the features, so if something that matters is not among them, the model cannot use it.
Numeric and categorical features
Most algorithms do arithmetic on features, so everything must become numbers.
- Numeric features, like weight in grams, are numbers already.
- Categorical features, like color, are names. Replacing them with 0, 1, 2 would wrongly suggest that "green" sits between "red" and "yellow". The standard fix is one-hot encoding: one new column per category, holding 1 if the sample has that category and 0 otherwise.
The example takes a few fruit records, splits off the label, and one-hot encodes the color so every sample becomes a list of numbers of the same length.
Expected output
feature names: ['weight', 'color_green', 'color_orange', 'color_red', 'color_yellow'] [150, 0, 0, 1, 0] -> apple [120, 0, 0, 0, 1] -> lemon [170, 0, 1, 0, 0] -> orange [140, 1, 0, 0, 0] -> apple [110, 0, 0, 0, 1] -> lemon samples: 5 features per sample: 5
Each printed vector has the same layout, described by the feature names line: weight first, then one column per color. Libraries such as scikit-learn provide this as OneHotEncoder, but the idea is exactly what the loop does.
Choosing features
Good features carry information about the label. Weight and color help tell fruits apart; the day the fruit was weighed probably does not. Two warnings apply:
- Leakage: never include a feature that secretly contains the answer, such as a "refund issued" column when predicting whether an order will be returned. The model will look brilliant in testing and fail in real use.
- Sensitive attributes: features like age or postal code can encode information about protected groups. Using them needs deliberate thought, a topic for the responsible AI chapter.
Summary
- Samples are rows, features (
X) are inputs, the label or target (y) is the answer. - Everything becomes numbers; one-hot encode categories instead of numbering them.
- Pick informative features and watch for leakage.
Quiz: Features and labels