Sub topic 9
Preparing data: scaling, categorical features, missing values
This chapter assumes you can use pandas and scikit-learn pipelines, and that you know how an isolation tree picks a random feature and a random split value. Here you decide which preprocessing steps help Isolation Forest and which are unnecessary.
Scaling: mostly unnecessary
An isolation tree picks a feature at random. It then picks a split value uniformly between that feature's minimum and maximum in the current node. No distances are computed, so features with large units do not dominate the way they do in k-NN or k-means.
Standardizing or min-max scaling is a linear rescaling. It does not change how the splits are distributed, so it gives you essentially the same model. Skip it unless another step in your pipeline needs it.
Non-linear transforms do change the result. A heavy-tailed feature such as transaction amount has a range set by its most extreme values. Uniform splits then rarely fall inside the dense region, and ordinary points get separated slowly. Taking log1p of such a feature spreads the normal points out. This can make the detector less sensitive to the extremes, so apply it only where the skew reflects scale and not the anomalies you are looking for.
Categorical features
Trees in scikit-learn need numbers, so you must encode categories. The two usual choices behave differently:
| Encoding | Effect on isolation | Risk |
|---|---|---|
| One-hot | Each category becomes a 0/1 column. A rare category is isolated by one split on its column. | High-cardinality features add many sparse columns and dilute the numeric features. |
| Ordinal | One column, with split values between integer codes. | Imposes an arbitrary order, so "red < green < blue" has no meaning. |
Prefer one-hot for low-cardinality features. For features with hundreds of levels, consider frequency encoding or dropping the feature. With one-hot columns, a rare category tends to look anomalous. This is often what you want, but it is a decision you are making.
Missing values
Isolation Forest compares values to split points, so a missing value needs a defined treatment. Support for NaN inputs depends on your scikit-learn version, and many versions raise a ValueError. Check the documentation for the version you run, and impute explicitly for predictable behavior.
Use SimpleImputer with add_indicator=True. Median imputation puts missing rows at the center of the feature, where they look normal. The indicator column keeps the information that the value was missing, so rows with unusual missingness can still be isolated.
A complete pipeline
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import IsolationForest
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder
rng = np.random.RandomState(0)
n = 300
df = pd.DataFrame({
"amount": rng.lognormal(3, 0.5, n),
"age": rng.normal(40, 10, n),
"channel": rng.choice(["web", "app", "store"], n),
})
df.loc[rng.choice(n, 15, replace=False), "age"] = np.nan
df.loc[0, "amount"] = 50000.0 # planted anomaly
pre = ColumnTransformer([
("age", SimpleImputer(strategy="median", add_indicator=True), ["age"]),
("amount", FunctionTransformer(np.log1p), ["amount"]),
("channel", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["channel"]),
])
model = Pipeline([
("prep", pre),
("iforest", IsolationForest(random_state=0)),
]).fit(df)
df["anomaly_score"] = -model.score_samples(df) # higher = more anomalous
print(df.nlargest(3, "anomaly_score"))Keeping the preprocessing and the model in one Pipeline means the same imputation values and category lists are applied at prediction time.
Common errors
- Standardizing every column "just in case". It costs nothing but changes nothing.
- Ordinal-encoding unordered categories, which creates fake structure.
- Filling missing values with 0, which can place those rows at an extreme and flag them for the wrong reason.
- Forgetting
handle_unknown="ignore", so a new category at prediction time raises an error.
Exercise
A feature "income" is heavily right-skewed, and a few very large values are legitimate high earners, not anomalies. Without any transform, why might Isolation Forest perform poorly, and what would you try?
Show answer
Split values are drawn uniformly between the feature's minimum and maximum, and the huge values stretch that range. Most splits then fall in the empty space above the bulk of the data, so ordinary points are separated slowly and scores for the dense region become less informative. Apply a log transform such as log1p to compress the range, then refit.