Normalize classification targets
A classifier expects target labels in a compact integer representation.
Scikit-Learn · Class
LabelEncoder converts target labels into integer codes from 0 to n_classes - 1 and can convert those codes back. It is for y, not input features X.
LabelEncoder learns the distinct values in a target array and stores them in classes_. It maps each value to an integer from 0 through the number of classes minus 1, and inverse_transform converts those integers back to the original labels.
class sklearn.preprocessing.LabelEncoder()| Name | Type | Description |
|---|---|---|
y | array-like of shape (n_samples,) | Target values used to fit the encoder; an array-like collection with one value per sample. |
fit returns the fitted LabelEncoder; transform and fit_transform return an ndarray of encoded labels; inverse_transform returns the original labels.
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
encoded = encoder.fit_transform(["paris", "tokyo", "paris"])
print(encoded.tolist())
print(encoder.classes_.tolist())
print(encoder.inverse_transform(encoded).tolist())Fits the encoder, converts target labels to integer codes, and restores the original labels.
A classifier expects target labels in a compact integer representation.
A pipeline needs to store and later restore human-readable target names.
Targets are strings or other comparable, hashable values.
LabelEncoder is intended for encoding the prediction target y. It learns the unique target values and represents them with integers from 0 to n_classes - 1.
Follow-up: How would you encode categorical input features? Use a feature-oriented encoder such as OneHotEncoder or OrdinalEncoder instead of LabelEncoder.
fit learns the labels and stores them in classes_. transform maps labels to their learned integer codes, while fit_transform performs fitting and encoding in one operation.
Follow-up: What does inverse_transform do? It maps encoded integers back to the corresponding original labels using the learned class mapping.
The classes_ attribute contains the label for each class, and the encoded values correspond to the positions of those classes. The documentation's examples show both numeric and non-numeric labels being converted and then recovered.
Follow-up: What must hold for string labels? They must be hashable and comparable so the encoder can process them.
sklearn.preprocessing.OrdinalEncodersklearn.preprocessing.OneHotEncodersklearn.preprocessing.LabelBinarizer