Sensitivity in Feature Engineering

Sensitivity in feature engineering means how much a model’s behavior depends on choices about representation โ€” which scale, which encoding, which transformation โ€” rather than on the data itself. A sensitive pipeline is one where a decision made for convenience changes the answer.

(The word has a different, more common meaning in classification: sensitivity as a synonym for recall. This article is about the first sense.)

How much the encoding can matter

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

rng = np.random.default_rng(0)
n, k = 8000, 6
color = rng.integers(0, k, size=n)
effect = np.array([2.0, -2.0, 2.0, -2.0, 2.0, -2.0])
"""Six unordered categories. Adjacent codes have opposite effects, so no integer
   ordering of them carries the signal in a straight line."""
y = (rng.random(n) < 1 / (1 + np.exp(-effect[color]))).astype(int)

one_hot = np.eye(k)[color]
for name, make in (("logistic regression", lambda: LogisticRegression(max_iter=1000)),
                   ("random forest", lambda: RandomForestClassifier(n_estimators=100, random_state=0))):
    as_int = cross_val_score(make(), color.reshape(-1, 1).astype(float), y, cv=5).mean()
    as_ohe = cross_val_score(make(), one_hot, y, cv=5).mean()
    print(f"  {name:<20} category as an integer {as_int:.4f}   one-hot encoded {as_ohe:.4f}")

print(f"\n  the accuracy of the best per-category rule on this sample is {np.mean(y == (effect[color] > 0)):.4f}")
orders = [rng.permutation(k) for _ in range(5)]
scores = [cross_val_score(LogisticRegression(max_iter=1000),
                          np.argsort(o)[color].reshape(-1, 1).astype(float), y, cv=5).mean()
          for o in orders]
print(f"  five arbitrary relabelings of the same six categories, as integers, for logistic regression:")
print("   " + "  ".join(f"{s:.4f}" for s in scores))
#   logistic regression  category as an integer 0.6346   one-hot encoded 0.8799
#   random forest        category as an integer 0.8799   one-hot encoded 0.8799
#
#   the accuracy of the best per-category rule on this sample is 0.8799
#   five arbitrary relabelings of the same six categories, as integers, for logistic regression:
#    0.8799  0.3775  0.6220  0.6220  0.6232

Six unordered categories. The best per-category rule (predict the more likely label for each category) scores 0.8799 on this sample, and one-hot encoding reaches it. The generating model’s own ceiling is slightly different, \(1/(1+e^{-2})\approx 0.8808\), because the sample frequencies differ a little from the probabilities.

Handing the same categories to logistic regression as integers gives 0.6346, because a linear model applies one coefficient to that column and can only express “higher code, higher probability.” With effects that alternate between adjacent codes, no single slope fits.

The last line is the one worth keeping. Relabeling the same six categories arbitrarily โ€” the order a database happens to return them in, or alphabetical order, or the order they were first seen โ€” gives 0.8799, 0.3775, 0.6220, 0.6220 and 0.6232. Same data, same model, same task. One arbitrary permutation matches that best per-category rule; another lands at 0.3775, worse than guessing.

The random forest scores 0.8799 under both encodings in this run. That is an observed result, not immunity to integer ordering. A tree with enough splits can isolate any subset of codes, but a depth-limited greedy fit may change when the codes are permuted. With three categories and only the middle code positive, a depth-one tree can reach accuracy 2/3; moving that category to an endpoint allows accuracy 1.

(The data here is built so that adjacent codes have opposite effects. Real categories are sometimes numbered in an order that happens to be useful, and then integer codes work. The point is that this is luck, and it is not visible from the code column.)

Where sensitivity comes from

  • Scale, for anything that measures distance. k-nearest neighbors, clustering, kernel methods and PCA all read the units, and the article on normalization measures a nine-point accuracy swing from that alone. Linear models are nearly immune; trees are exactly immune.
  • Encoding, for linear models and constrained tree fits. Arbitrary integer ordering can change the available splits; depth and fitting choices determine how much the score changes.
  • Grouping decisions. Where you set the “fold rare levels into other” threshold changes both the feature and the statistics computed on it, and cardinality shows association measures moving from 0.0166 to 0.6057 on data with no association at all.
  • Outliers in fitted transformations. One mistyped value redefines a minโ€“max range and moves every other row.

A pattern runs through those: the choices that matter most are the ones that get made without deliberation, because they are defaults. Nobody decides to use alphabetical ordering for a nominal column โ€” it is what the library returned.

Measuring it instead of reasoning about it

The useful move is to treat sensitivity as something to test rather than avoid. Pick the arbitrary choices in the pipeline, vary them, and see what happens to the score.

  • Re-number the categories at random and refit. If the score moves, the model is reading an order that does not exist.
  • Swap the scaler โ€” standard for robust, or none at all. A large change says the pipeline depends on distributional assumptions worth stating.
  • Move the rare-category threshold and see whether conclusions survive.
  • Change the random seed of everything that has one. A result that moves under reseeding was never a result.

Each of these costs one refit and turns an assumption into a number. Reporting that number โ€” “accuracy varies by less than 0.005 across ten re-encodings” โ€” is worth more than a statement that the encoding was chosen carefully.

The reductions themselves are the familiar ones: scale numeric features for distance-based models, one-hot unordered categories for linear ones, use ordinal encoding only where an order genuinely exists, and regularize so that no single representation choice dominates. The article on categorical encoding covers the choices in detail โ€” this one is about knowing how much they are costing you.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.