CodeBlanks Logo Icon CodeBlanks

Categorical features

Categorical features are converted to binary vectors with OneHotEncoder.

Categorical features

Text columns with a limited set of values, like city, colour or product type, are categorical. Unordered categories are encoded with one-hot, ordered ones (small < medium < large) with OrdinalEncoder:

from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
sehir = [["Ankara"], ["İzmir"], ["Ankara"]]
print(OneHotEncoder().fit_transform(sehir).toarray())
boy = [["küçük"], ["büyük"], ["orta"]]
oe = OrdinalEncoder(categories=[["küçük", "orta", "büyük"]])
print(oe.fit_transform(boy).ravel())   # [0. 2. 1.]

Without categories, OrdinalEncoder uses alphabetical order, which is often not the meaningful order.

Unknown categories and rare values

New categories are inevitable in production; handle_unknown="ignore" handles them safely. If there are many rare categories, min_frequency groups them into a single "infrequent" column:

enc = OneHotEncoder(handle_unknown="ignore")
enc.fit([["Ankara"], ["İzmir"]])
print(enc.transform([["Bursa"]]).toarray())   # [[0. 0.]]

For columns with thousands of distinct values (like product codes), one-hot produces very wide matrices; methods like target encoding are considered then.

Practice Ordinal encode

Encode the egitim column with OrdinalEncoder(categories=[["lise", "lisans", "doktora"]]) and print the result with ravel().

Starter code

model.py
from sklearn.preprocessing import OrdinalEncoder

egitim = [["lisans"], ["lise"], ["doktora"], ["lisans"]]

# buraya yaz

Sample solution

model.py
from sklearn.preprocessing import OrdinalEncoder

egitim = [["lisans"], ["lise"], ["doktora"], ["lisans"]]

oe = OrdinalEncoder(categories=[["lise", "lisans", "doktora"]])
print(oe.fit_transform(egitim).ravel())

Expected output

[1. 0. 2. 1.]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If a city not seen in training appears in the test data, what does OneHotEncoder do by default?

  • It uses the most frequent city
  • It errors Correct answer
  • It opens a new column
  • It uses zeros

Explanation: With handle_unknown="ignore", the unknown value becomes an all-zero row.

2 Handle unknown categories without errors.

Question
enc = OneHotEncoder(handle_unknown=____)
Answer
enc = OneHotEncoder(handle_unknown="ignore")

Explanation: "ignore" turns an unknown value into a zero vector.

3 Match the encodings.

Term Meaning
Color One-hot
Size S/M/L Ordinal encoding
New city handle_unknown
Rare categories min_frequency

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation