Sub topic 9
Preparing data: scaling, categorical features, missing values
This chapter assumes you can build a pandas DataFrame, know what a scikit-learn Pipeline and ColumnTransformer are, and have read the earlier chapters on how isolation trees choose random splits. Here you decide which preprocessing steps help an Isolation Forest, which ones do nothing, and which ones quietly change what counts as "anomalous".
Why preprocessing works differently here
Distance-based and gradient-based models are sensitive to feature scale. Isolation Forest is not, because of how a tree is built. At each node it does the following:
- It picks one feature uniformly at random.
- It draws a split value uniformly between the minimum and maximum of that feature among the points in the node.
- It sends points left or right and repeats.
No distances are computed and no feature is weighted by its variance. Every step compares one feature's values against a threshold, so the algorithm depends only on the order of values and on where the minimum and maximum sit. That has three consequences:
- Affine rescaling of a feature (multiplying by a positive constant, adding a constant) does not change the distribution of splits.
- Monotonic but non-linear transforms (log, square root, rank) do change it, because "uniform between min and max" is not preserved.
- Everything must be numeric, since the splits are numeric comparisons.
Scaling: mostly unnecessary
Standardizing a feature moves and stretches it, but the random split still lands at the same relative position within the node's range. With the same random_state, a forest fitted on raw data and a forest fitted on standardized data should build the same trees and give the same scores, apart from floating-point noise. A log transform is a different case. It changes which points are "extreme", so the scores change.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
rng = np.random.RandomState(1)
X = np.column_stack([
rng.normal(50, 10, size=600), # feature on a scale of tens
rng.normal(0.001, 0.0002, size=600), # feature on a scale of 1e-3
])
raw = IsolationForest(random_state=7).fit(X)
scaled = IsolationForest(random_state=7).fit(StandardScaler().fit_transform(X))
diff = np.abs(raw.score_samples(X) - scaled.score_samples(StandardScaler().fit(X).transform(X)))
print("max score difference after scaling:", diff.max()) # expected to be tiny
# A log transform is not affine, so it does change the scores
X_pos = np.abs(X) + 1e-6
logged = IsolationForest(random_state=7).fit(np.log(X_pos))
print("mean score raw vs log:", raw.score_samples(X).mean(), logged.score_samples(np.log(X_pos)).mean())Scaling is harmless, so it is fine to keep a StandardScaler in a shared pipeline. Just do not expect it to fix anything.
When a transform does matter
Consider a feature like transaction amount, where most values are between 1 and 100 and a few legitimate values reach 1,000,000. The split value is uniform over the whole range, so almost every split falls among the huge values and separates only the very largest points. The ordinary points cluster together and are rarely separated from each other. Two things follow:
- The few huge-but-legitimate values are isolated almost immediately and look anomalous. That may be what you want, or it may be a false-positive generator.
- Differences inside the dense region carry little signal, because few splits land there.
A log1p transform spreads the dense region out and pulls the tail in. Use it when you care about relative differences (a 10x jump) more than absolute ones. Skip it when large absolute values are exactly the anomalies you are hunting.
Categorical features
IsolationForest accepts only numeric input, so strings must be encoded. Each encoding changes the trees you get.
| Encoding | What the forest sees | Main risk |
|---|---|---|
| One-hot | One 0/1 column per category | Many columns dilute the numeric features, since each column is picked with equal probability |
| Ordinal | One integer column | Invents an order. Splits group arbitrary neighbours, such as codes 2 and 3 |
| Frequency or count | One column holding how common each category is | Loses category identity. Two different rare categories look alike |
How each one behaves:
- One-hot. A binary column always splits into "has this category" and "does not". A rare category is separated from the rest in a single split whenever that column is chosen. This makes rare categories look anomalous, which is often desirable, but it also pushes all rare-but-valid categories toward high scores. With 50 one-hot columns and 3 numeric columns, about 94% of splits are spent on category columns, so numeric outliers are found more slowly. The effect shows up when you set
max_featuresbelow 1.0 as well. - Ordinal. Fine when the categories really have an order, such as size S, M, L. For unordered categories, the order is an artefact. A category coded in the middle of the range takes more splits to isolate than one coded at either end, for reasons unrelated to the data.
- Frequency. Gives one column that directly states "how rare is this category". It works well when rarity is the signal, and it avoids column blow-up for high-cardinality features such as ZIP codes.
For a high-cardinality column, prefer frequency encoding or drop the column. One-hot encoding thousands of categories makes the forest mostly random noise over sparse binary columns.
Missing values
The behaviour of IsolationForest on NaN depends on your scikit-learn version. Older releases raise a ValueError on missing values. Newer releases may accept them in some cases. Check your installed version before relying on it, and prefer explicit handling so results do not change on upgrade.
The reliable approach is to impute and also record where values were missing. Missingness is often informative. A record with a missing field may itself be unusual, and a single imputed constant can hide that.
- Median imputation keeps the filled value inside the dense region, so imputed rows are not made to look extreme by the imputation.
- A missing-indicator column (
add_indicator=True) lets the forest isolate rows by "was missing", which rare missingness patterns make easy. - A sentinel such as -999 is risky. It stretches the min-max range of the feature, which pushes every split into the empty gap, and it flags every imputed row as an extreme outlier.
A complete pipeline
The following example builds a mixed-type DataFrame with missing values, a skewed amount column and a categorical column, then fits everything in one Pipeline. Fitting the preprocessing inside the pipeline means the imputer medians and category lists come from the training data only.
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(3)
n = 800
df = pd.DataFrame({
"amount": rng.lognormal(mean=3.0, sigma=0.6, size=n),
"age": rng.normal(40, 8, size=n),
"country": rng.choice(["DE", "FR", "ES"], size=n, p=[0.5, 0.3, 0.2]),
})
# Inject a few anomalies and some missing values
df.loc[:4, "amount"] = [5000, 7000, 9000, 6500, 8000]
df.loc[5:9, "country"] = "ZZ"
df.loc[rng.choice(n, 40, replace=False), "age"] = np.nan
df.loc[rng.choice(n, 20, replace=False), "country"] = np.nan
numeric = Pipeline([
("impute", SimpleImputer(strategy="median", add_indicator=True)),
])
amount = Pipeline([
("log", FunctionTransformer(np.log1p)),
])
categorical = Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="missing")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
])
prep = ColumnTransformer([
("amount", amount, ["amount"]),
("age", numeric, ["age"]),
("country", categorical, ["country"]),
])
model = Pipeline([
("prep", prep),
("forest", IsolationForest(n_estimators=200, random_state=0)),
]).fit(df)
df["score"] = model.score_samples(df)
print(df.sort_values("score").head(10))A few details in this code matter:
handle_unknown="ignore"means a new category seen at scoring time becomes an all-zero row instead of raising an error. The forest then sees it as "none of the known countries", which is usually treated as unusual.sparse_output=Falseneeds scikit-learn 1.2 or later. In older versions the argument is calledsparse.add_indicator=Trueappends a 0/1 column for theagecolumn's missingness. It only creates a column for features that had missing values duringfit.Pipeline.score_samplespasses data through the preprocessing and calls the forest'sscore_samples. Lower values are more abnormal, as in earlier chapters.
Common mistakes
- Fitting the imputer or encoder on all data, including test data. This leaks information about the data you will score later. Keep preprocessing inside the pipeline.
- Scaling and then expecting different results. If scores change after scaling, check for a changed
random_stateor a non-affine step. - Dropping the ID column too late. A numeric ID that grows over time is a numeric feature like any other. The forest will use it, and rows with extreme IDs become outliers for no real reason. Remove identifiers and raw timestamps before fitting.
- Treating duplicates and constants as harmless. A constant column is never split usefully but still takes its share of feature draws. Remove it with
VarianceThreshold.
Exercise
A data set has 3 numeric features and 1 categorical feature with 40 categories. A colleague one-hot encodes the categorical feature and fits an Isolation Forest with the default max_features=1.0. Numeric outliers are scored poorly. Give the likely cause and two fixes.
Show answer
After one-hot encoding there are 43 columns, and each split picks a column uniformly among them. The three numeric columns get only about 7% of the draws, so numeric outliers are isolated slowly and look ordinary. Two fixes: replace the one-hot columns with a single frequency-encoded column (or drop the categorical feature if it is not informative), which restores the numeric features' share of splits. Alternatively, fit separate forests for the numeric and categorical parts and combine their scores. Raising n_estimators does not fix the imbalance.