Build an Employee Attrition Predictor with Random Forests and Feature Importance


classical-ml feature-engineering model-evaluation
View full code for this problem

ML Problem & Solution

Attrition Prediction and Honest Feature Importance

The model is easy. The explanation HR will act on is where this problem goes wrong.

⏱ 21 min read 📐 Intermediate 🧮 Classical ML

A 12,400 person company loses 14.8% of its people to voluntary resignation each year. Finance costs a departure at somewhere between 0.6 and 1.8 times salary once you count recruiting fees, the vacancy gap, and the eight months a replacement takes to reach full productivity, which puts the annual bill somewhere near 41 million dollars. The People team has capacity to run roughly 200 structured retention conversations a quarter, each of which costs a manager’s time and a genuine budget concession: an off-cycle raise, a title change, a transfer, a project reassignment. They want a model that tells them which 200 people.

Then they ask the question that makes this a different problem from churn prediction: they want to know why. Not for the individual, particularly, but in aggregate. If the model says compensation is the dominant driver, the answer is a mid-year salary review costing 6 million dollars. If it says manager quality dominates, the answer is a management training program and some difficult reassignments. If it says promotion velocity dominates, the answer is restructuring the career ladder. These are not interchangeable, they cost different amounts, and the feature importance table is the artifact that decides between them. The ranking gets the 200 names; the importances get the budget.

That is where this problem goes wrong, and it goes wrong quietly. Fit a random forest, call model.feature_importances_, sort descending, and put the top ten in a slide. The number that comes back is mean decrease in impurity, and it has a well documented bias: it inflates the apparent importance of continuous and high-cardinality features, because a feature with many distinct values offers many candidate split points and so has more opportunity to look good on a bootstrap sample by chance. Strobl and colleagues demonstrated this in 2007 with an experiment worth reproducing on your own data: add a column of pure random noise with many distinct values and watch it climb the importance ranking. On this dataset a randomly generated employee identifier hash lands fourth, above manager tenure and above promotion wait time. Nobody looking at that slide can tell which of the other entries are real.

The analogy is a lineup where the witness has been shown the suspects for wildly different lengths of time. The person they looked at longest feels most familiar, and familiarity gets mistaken for recognition. Impurity importance measures how often a feature was useful for splitting, which conflates how predictive a feature is with how many chances it got.

Given each employee’s compensation, tenure, role, manager, performance, and engagement attributes as of a quarter-end snapshot, predict whether they will voluntarily resign in the following 12 months, optimizing precision in the top 200 ranked employees, and produce feature importances that survive a permutation test on held-out data.

Framing the Problem

This is binary classification on a small, moderately imbalanced tabular dataset, where the explanation is a co-equal deliverable with the prediction. That last clause is not softness about interpretability. It changes the model class we can consider, the importance method we use, and what counts as success.

The target is left_voluntarily_12m: the employee resigned of their own accord within 365 days of the snapshot date. Three exclusions in that definition are load-bearing.

Involuntary exits are not positives, and they are not negatives either. Terminations for performance, redundancies, and role eliminations are a different process with different drivers, and a model trained on “left the company” learns a blend of two unrelated things. There were 412 involuntary exits in the window. They are removed from the population entirely rather than labeled zero, because an employee who was fired in month 4 was never given the chance to resign in month 9.

Retirements are excluded. They are highly predictable from age, they are not preventable by a retention conversation, and including them lets the model score well on a population the intervention cannot help. This is the single easiest way to inflate this model’s apparent performance.

Regretted and non-regretted attrition are different targets. About 23% of voluntary departures are people the company was not sorry to lose. The People team’s capacity should not be spent on them. We model all voluntary attrition and then re-rank by a regret weight derived from the last performance rating, rather than trying to learn a “regretted resignation” label directly, because that label is noisy and manager-dependent.

Constraints

  • Small n, and it is the binding constraint. 12,400 employees, 22 months of quarterly snapshots, and after deduplication roughly 1,830 positive events. A deep model has nothing to learn from here, and any conclusion drawn from a subgroup of 40 people is noise.
  • Legal and fairness constraints. Protected attributes (age, gender, race, disability status, pregnancy, marital status) are excluded from the feature set. That is necessary and nowhere near sufficient: commute distance proxies for neighborhood, which proxies for race in most cities. The flagged set gets an explicit disparate impact test before anyone sees a name.
  • Explanations must be aggregate-stable. The importance ranking has to be stable enough that it does not reorder between quarterly refits, because it is being used to allocate an annual budget. An importance method whose top five changes every quarter is not usable regardless of how accurate the underlying model is.
  • Actionability. tenure_months is likely to be predictive and there is nothing to do about it. The intervention menu is compensation, promotion, manager, team, and scope, so the importance table that matters is restricted to features the company can actually move.
  • The intervention destroys the label. If a retention conversation works, the employee stays, and the model that flagged them looks wrong. This is a real measurement problem and it is why the evaluation uses a holdout the People team is not allowed to act on.
Metric That Matters

Precision at 200, written P@200, matched to the quarterly intervention capacity. Of the 200 employees the model ranks highest, what fraction actually resign within 12 months. The base rate is 14.8%, so random selection gives 14.8% and a useful model has to clear that by a wide margin. This is the right headline metric because the capacity is genuinely fixed: there is no version of this project where the People team runs 1,400 retention conversations, so model quality at any other operating point is irrelevant. accuracy is actively misleading here, since predicting that nobody leaves scores 85.2%, and ROC-AUC averages over the whole ranking when only the top 1.6% of it will ever be looked at.

Guardrail metrics: PR-AUC as the threshold-free summary, lift at 200 against the base rate, calibration error in the top two deciles (because a manager told an employee is at 70% risk will behave differently than one told 30%), demographic composition of the flagged set against the eligible population, and the quarter-over-quarter rank correlation of the feature importance table.

Out of scope: the causal question of whether any intervention reduces attrition. This model ranks risk. It cannot tell you that a raise will retain someone, and treating a high importance score for comp_ratio as evidence that raises work is the most expensive mistake available on this project. That question needs an experiment, and the closing section says how to run one.

Key Insight

When the explanation is a deliverable, the importance method becomes a modeling decision with the same weight as the model class, and it needs its own validation. The usual workflow validates the classifier with cross-validation and then reads `feature_importances_` as though it were a property of the world rather than an output of an estimator with its own bias and variance. It is an estimate, it has a known bias toward high-cardinality features, and it can and should be tested: inject a column of noise and see where it ranks. If noise lands in the top five, every conclusion drawn from that table is unsupported.

Data and Features

The unit of observation is an employee-quarter snapshot. 12,400 employees across 8 quarterly snapshots gives 94,300 employee-quarters after removing employees who had already left, though the effective sample size is far smaller than that because the same person appears up to 8 times.

Source Grain Fields used Notes
hris_snapshot employee x quarter 31 role, level, org path, manager, location, FTE status
compensation employee x change 9 base, bonus target, equity grants, band midpoint
performance employee x cycle 6 rating, calibration band, manager narrative length
engagement_survey employee x wave 12 aggregated to team level at n>=6 to preserve anonymity
learning employee x course 4 completions, hours, internal mobility applications
terminations employee 5 date, type, regret flag, stated reason
Attrition modeling pipeline: quarterly snapshots feeding a 12 month label horizon, grouped split by employee, random forest ranking, and the honest importance path using held-out permutation importance with grouped correlated features

The features that carry signal

We use 43 features in six groups. The groups matter more than the individual columns, for a reason the importance section makes concrete.

# Feature construction from a quarter-end snapshot. Everything here is
# knowable as of `snapshot_date`; nothing reads forward.
import numpy as np
import pandas as pd


def build_features(snap: pd.DataFrame, comp: pd.DataFrame,
                   perf: pd.DataFrame, survey: pd.DataFrame,
                   snapshot_date: pd.Timestamp) -> pd.DataFrame:
    feats = snap[["employee_id", "level", "job_family", "org_l2", "location",
                  "manager_id", "is_remote", "fte_pct"]].copy()

    # Compensation, expressed as position in band rather than absolute dollars.
    # comp_ratio is the single most portable compensation feature: it is
    # comparable across job families, levels, and geographies in a way that
    # base_salary is not.
    latest_comp = (comp[comp["effective_date"] <= snapshot_date]
                   .sort_values("effective_date")
                   .groupby("employee_id").tail(1))
    feats = feats.merge(latest_comp[["employee_id", "base_salary",
                                     "band_midpoint", "bonus_target_pct",
                                     "unvested_equity_value"]],
                        on="employee_id", how="left")
    feats["comp_ratio"] = feats["base_salary"] / feats["band_midpoint"]

    # Time since the last raise, and its size. A long flat period is a much
    # stronger signal than a low absolute salary.
    raises = comp[(comp["effective_date"] <= snapshot_date)
                  & (comp["change_type"] == "merit")]
    last_raise = raises.groupby("employee_id")["effective_date"].max()
    feats["months_since_raise"] = (
        (snapshot_date - feats["employee_id"].map(last_raise)).dt.days / 30.44)
    feats["last_raise_pct"] = feats["employee_id"].map(
        raises.sort_values("effective_date").groupby("employee_id")
        ["change_pct"].last())

    # Tenure and promotion velocity. months_in_level against the median for
    # that level is the feature that captures "overdue" without hard-coding a
    # policy that differs by job family.
    feats["tenure_months"] = (
        (snapshot_date - snap["hire_date"]).dt.days / 30.44).to_numpy()
    feats["months_in_level"] = (
        (snapshot_date - snap["level_start_date"]).dt.days / 30.44).to_numpy()
    level_median = feats.groupby("level")["months_in_level"].transform("median")
    feats["level_overdue_ratio"] = feats["months_in_level"] / level_median

    # Manager features. Span and manager tenure are the two that survive
    # permutation testing; manager's own performance rating does not.
    mgr = snap.groupby("manager_id").agg(
        mgr_span=("employee_id", "nunique"))
    feats = feats.merge(mgr, left_on="manager_id", right_index=True, how="left")
    mgr_start = snap.set_index("employee_id")["mgr_assignment_date"]
    feats["months_with_manager"] = (
        (snapshot_date - feats["employee_id"].map(mgr_start)).dt.days / 30.44)

    # Performance, using only cycles closed before the snapshot.
    closed = perf[perf["cycle_close_date"] <= snapshot_date]
    latest_perf = closed.sort_values("cycle_close_date").groupby(
        "employee_id").tail(1)
    feats = feats.merge(latest_perf[["employee_id", "rating_numeric",
                                     "calibration_band"]],
                        on="employee_id", how="left")
    prior = closed.sort_values("cycle_close_date").groupby(
        "employee_id")["rating_numeric"].apply(
        lambda s: s.iloc[-2] if len(s) >= 2 else np.nan)
    feats["rating_delta"] = feats["rating_numeric"] - feats[
        "employee_id"].map(prior)

    # Engagement, at TEAM level only. Individual survey responses are
    # confidential and using them would break the anonymity promise that makes
    # the survey worth anything.
    team_survey = (survey[survey["wave_date"] <= snapshot_date]
                   .sort_values("wave_date").groupby("team_id").tail(1))
    feats = feats.merge(team_survey[["team_id", "team_engagement_score",
                                     "team_manager_score",
                                     "team_response_rate"]],
                        left_on="org_l2", right_on="team_id", how="left")

    # Internal mobility: applying for an internal role is one of the strongest
    # single predictors, and is a genuine behavioural signal rather than a
    # demographic one.
    feats["internal_applications_6m"] = _mobility_count(snapshot_date, months=6)
    return feats.drop(columns=["manager_id", "team_id"])

Leakage here is subtle and there is a lot of it

Attrition data is full of fields that are written down because someone was leaving. Every one of them produces a model that looks superb offline and is useless in production, because at scoring time you are asking about people who have given no indication of anything.

Post-decision administrative traces. Declining benefits open enrollment, drawing a PTO balance to zero, a lapsed laptop refresh, an unusually short manager narrative in the final review cycle. These are consequences of a decision already made. Including benefits_declined alone takes held-out ROC-AUC from 0.814 to 0.923, which is the tell rather than the win.

Fields updated retroactively. The HRIS manager_id field is often corrected after a reorg, so a snapshot pulled from the current table shows the post-reorg manager for a historical quarter. The reorg itself may be why the person left. Snapshots must come from an as-of view or a change log, never from the live table.

Employee identity across the split. The same person appears in up to 8 snapshots. A random row-level split puts Q1 and Q3 of the same employee on opposite sides, and since most features are near-constant quarter to quarter, the model memorizes individuals. Measured cost: held-out ROC-AUC reads 0.887 instead of 0.814, a 0.073 inflation that is entirely fictional.

Survivorship in the snapshot population. Building snapshots by filtering the current employee table to people with a hire date before the snapshot silently excludes everyone who already left, which is exactly the positive class for earlier quarters.

There is a trap in fixing that last one, and it is worth showing because the obvious fix is wrong. If you take the final two quarters as test and then remove every test employee from the training pool, you have removed almost everyone who is still employed, because almost everyone still employed appears in the final quarters. What remains in train is overwhelmingly people who had already left. On this data that produced a 70% positive rate in train against 10% in test, which is not a split so much as two unrelated problems.

Partition on employees first, then slice by time within each partition.

# Grouped, time-ordered split. Employees are partitioned first and only then
# sliced by time, so both separations survive: no individual crosses a split,
# and every test row is strictly later than every training row.
import numpy as np
import pandas as pd


def grouped_time_split(frame: pd.DataFrame, holdout_quarters: int = 2,
                       valid_frac: float = 0.25,
                       test_employee_frac: float = 0.25, seed: int = 11):
    """Partition employees, then take different quarters from each partition.

    train = train-group employees, earlier quarters
    valid = valid-group employees, earlier quarters
    test  = test-group  employees, final holdout_quarters quarters

    The time boundary measures whether the model survives a changing labour
    market. The employee partition measures whether it learned anything
    beyond individual identity.
    """
    quarters = sorted(frame["snapshot_date"].unique())
    test_quarters = set(quarters[-holdout_quarters:])
    early = frame[~frame["snapshot_date"].isin(test_quarters)]
    late = frame[frame["snapshot_date"].isin(test_quarters)]

    employees = np.asarray(sorted(frame["employee_id"].unique()))
    order = np.random.default_rng(seed).permutation(len(employees))
    n_test = int(round(len(employees) * test_employee_frac))
    test_ids = set(employees[order[:n_test]])
    modeling = employees[order[n_test:]]

    n_valid = int(round(len(modeling) * valid_frac))
    valid_ids = set(modeling[:n_valid])
    train_ids = set(modeling[n_valid:])

    train = early[early["employee_id"].isin(train_ids)].copy()
    valid = early[early["employee_id"].isin(valid_ids)].copy()
    test = late[late["employee_id"].isin(test_ids)].copy()

    assert not (set(train["employee_id"]) & set(valid["employee_id"]))
    assert not (set(train["employee_id"]) & test_ids)
    assert test["snapshot_date"].min() > train["snapshot_date"].max()
    return train, valid, test


FORBIDDEN = {
    # Consequences of a resignation decision, not predictors of it.
    "benefits_declined", "pto_balance_zeroed", "exit_interview_scheduled",
    "laptop_refresh_declined", "final_review_narrative_length",
    "offboarding_ticket_open", "manager_notified_date",
    # Protected attributes. Excluded by policy, and proxies are tested
    # separately in the fairness check.
    "age", "gender", "race", "ethnicity", "disability_status",
    "marital_status", "pregnancy_status", "veteran_status",
}


def assert_feature_set_clean(columns) -> None:
    """Make leakage and protected-attribute use a build failure."""
    violations = FORBIDDEN & set(columns)
    if violations:
        raise AssertionError(
            f"forbidden columns present: {sorted(violations)}. "
            "Post-decision traces inflate held-out AUC by 0.10 or more and "
            "are unavailable at scoring time; protected attributes are "
            "excluded by policy."
        )
Common Pitfall

Splitting employee-quarter rows randomly. It is the natural thing to do because the rows look independent, and it is wrong because they are not: the same person contributes up to 8 of them and most features barely move between consecutive quarters. The model learns to recognize individuals, and since an individual's label is constant across their snapshots, recognizing the person is equivalent to knowing the answer. Held-out ROC-AUC reads 0.887 under a random split and 0.814 under a grouped split, and the second number is the real one. Group by employee, and put the final two quarters aside as a time-based test on top of that.

The Naive Baseline

Two baselines on the held-out final two quarters: 3,110 employee-quarters, 461 of whom resigned within 12 months, a 14.8% base rate.

# Baseline 1: majority class, which establishes that accuracy is unusable.
# Baseline 2: the heuristic HR already uses, which is tenure banding plus a
# salary flag. It is a real policy at a lot of companies and it is the
# thing to beat.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler


def majority_class(n: int) -> np.ndarray:
    # 85.2% accurate and 0% useful. Included so nobody celebrates 85%.
    return np.zeros(n, dtype=np.int8)


def hr_heuristic(feats: pd.DataFrame) -> np.ndarray:
    """Flag the 18-to-36 month tenure window plus below-band pay.

    Encodes the received wisdom that people leave in their second year and
    that underpaid people leave. Both are true and neither is sufficient.
    """
    in_window = feats["tenure_months"].between(18, 36)
    underpaid = feats["comp_ratio"] < 0.95
    # A score rather than a flag, so it can be ranked and compared at P@200.
    return (in_window.astype(float) * 2.0 + underpaid.astype(float)
            + (feats["months_since_raise"].fillna(0) / 24.0)).to_numpy()


def logistic_baseline(train: pd.DataFrame, test: pd.DataFrame,
                      columns: list[str]) -> np.ndarray:
    model = make_pipeline(
        StandardScaler(),
        LogisticRegression(max_iter=2000, class_weight="balanced"),
    )
    model.fit(train[columns].fillna(train[columns].median()),
              train["left_voluntarily_12m"])
    return model.predict_proba(
        test[columns].fillna(train[columns].median()))[:, 1]

Held-out results:

Baseline Accuracy ROC-AUC PR-AUC P@200 Lift@200
Majority class (nobody leaves) 85.2% 0.500 0.148 n/a n/a
HR tenure and pay heuristic 71.4% 0.612 0.211 24.0% 1.62x
Logistic regression, 6 features 79.8% 0.681 0.243 29.5% 1.99x

The first row is why accuracy cannot be used: 85.2% from a model with no inputs. Anyone reporting 85% accuracy on this problem is reporting the base rate.

The HR heuristic is the interesting baseline because it is what the model has to displace politically as well as statistically. It gets 24% precision in its top 200, which is 1.62 times better than random, and it is not nothing. Its weakness is that it is built from two features and cannot express interaction: an employee 30 months into their tenure who was promoted last quarter and sits at 1.04 comp ratio is flagged identically to one who has been flat for three years, because both fall in the tenure window. The logistic model with six features does better and is still additive by construction, so it cannot represent the thing that turns out to matter most here, which is that low pay is nearly irrelevant for someone recently promoted and highly predictive for someone who has been in the same level for 30 months.

The Solution

Fit a random forest with balanced subsample class weighting, then compute feature importance three ways and only trust what survives all three. The classifier is the easy half. The importance analysis is the part that changes what the company does with 6 million dollars.

Why a random forest here

At 1,830 positive events across 43 features, the binding constraint is variance, not bias. A random forest is a good fit for three specific reasons rather than as a default choice.

It captures interactions without being told which ones to look for, which is exactly the gap the logistic baseline could not close. Averaging over bootstrapped, feature-subsampled trees is a variance reduction device, which is what a small sample needs most. And it provides out-of-bag estimates, which at this sample size is a real advantage: every row gets an honest prediction from the roughly 37% of trees that did not see it, giving a validation signal without spending data on a separate fold.

Analogy for the mechanism: a single decision tree is one interviewer with strong opinions who will latch onto whatever stood out in the first five minutes. A random forest is 800 interviewers, each shown a random subset of the candidate’s answers and a random subsample of past candidates, voting. No individual is more reliable, and the average of their votes is, because their errors are mostly uncorrelated.

# The solution model. Hyperparameters chosen for a small-n, moderately
# imbalanced problem, not copied from a tutorial.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder

NUMERIC = ["comp_ratio", "base_salary", "bonus_target_pct",
           "unvested_equity_value", "months_since_raise", "last_raise_pct",
           "tenure_months", "months_in_level", "level_overdue_ratio",
           "mgr_span", "months_with_manager", "rating_numeric",
           "rating_delta", "team_engagement_score", "team_manager_score",
           "team_response_rate", "internal_applications_6m", "fte_pct"]
CATEGORICAL = ["level", "job_family", "org_l2", "location",
               "calibration_band", "is_remote"]

RF_PARAMS = {
    "n_estimators": 800,
    # Depth is left unbounded and regularization goes through leaf size
    # instead. On 43 features and 1,830 events, min_samples_leaf is the
    # parameter that actually controls overfitting.
    "max_depth": None,
    "min_samples_leaf": 12,
    "min_samples_split": 30,
    # sqrt(43) is about 6.5 features per split. Lower than the regression
    # default on purpose: several feature groups are highly correlated and
    # aggressive subsampling is what stops one group dominating every tree.
    "max_features": "sqrt",
    # balanced_subsample rather than balanced: weights are recomputed per
    # bootstrap sample, which matters at a 14.8% positive rate where some
    # bootstraps draw noticeably fewer positives than others.
    "class_weight": "balanced_subsample",
    "oob_score": True,
    "bootstrap": True,
    "n_jobs": -1,
    "random_state": 11,
}


def build_pipeline(params: dict = RF_PARAMS) -> Pipeline:
    pre = ColumnTransformer([
        ("num", SimpleImputer(strategy="median", add_indicator=True), NUMERIC),
        # Missingness in HR data is informative: a null rating_numeric usually
        # means the employee joined mid-cycle, which is itself a risk factor.
        # add_indicator keeps that signal instead of imputing it away.
        ("cat", OneHotEncoder(handle_unknown="ignore", min_frequency=25),
         CATEGORICAL),
    ])
    return Pipeline([("pre", pre),
                     ("rf", RandomForestClassifier(**params))])


def fit_forest(train: pd.DataFrame, params: dict = RF_PARAMS) -> Pipeline:
    pipe = build_pipeline(params)
    pipe.fit(train, train["left_voluntarily_12m"])
    oob = pipe.named_steps["rf"].oob_score_
    print(f"out-of-bag accuracy {oob:.4f} "
          f"(compare to the {1 - train['left_voluntarily_12m'].mean():.4f} "
          "majority-class floor before reading anything into it)")
    return pipe

min_samples_leaf = 12 is the hyperparameter that matters most, and it is a direct consequence of sample size. At the sklearn default of 1, leaves form around two or three employees, the model memorizes the training set (training ROC-AUC 0.998, held-out 0.771), and the importance ranking becomes unstable across refits. At 12, held-out ROC-AUC rises to 0.814 and the importance top five holds still between quarterly refits, which is the property the budget conversation needs.

Feature importance, done three ways

Here is the part that matters. We compute three importance measures and compare them, which takes about twenty lines of code and is the difference between a defensible recommendation and an expensive mistake.

# Three importance measures. Run all three; trust what agrees. The noise
# column is the control: anything ranked at or below it is indistinguishable
# from nothing.
import numpy as np
import pandas as pd
from sklearn.inspection import permutation_importance
from sklearn.metrics import average_precision_score


def add_noise_controls(frame: pd.DataFrame, seed: int = 3) -> pd.DataFrame:
    """Inject controls that must rank near the bottom of an honest table.

    `noise_highcard` is the diagnostic: it is pure noise with as many distinct
    values as there are rows, which is exactly the shape that mean decrease in
    impurity over-rewards. Strobl et al. (2007) is the reference.
    """
    rng = np.random.default_rng(seed)
    out = frame.copy()
    out["noise_highcard"] = rng.normal(size=len(out))
    out["noise_binary"] = rng.integers(0, 2, size=len(out))
    return out


def impurity_importance(pipe: Pipeline, names: list[str]) -> pd.Series:
    """Mean decrease in impurity: what `feature_importances_` returns.

    Fast, computed for free during training, and biased toward continuous and
    high-cardinality features, because a feature with many distinct values
    offers many candidate split points and so has more chances to look good on
    a bootstrap sample. Also computed on TRAINING data, so it rewards
    overfitting.
    """
    return pd.Series(pipe.named_steps["rf"].feature_importances_,
                     index=names).sort_values(ascending=False)


def holdout_permutation_importance(pipe: Pipeline, valid: pd.DataFrame,
                                   n_repeats: int = 30,
                                   seed: int = 7) -> pd.DataFrame:
    """Shuffle one column at a time and measure the drop in PR-AUC.

    Computed on HELD-OUT data, which is the point: it measures how much the
    model's generalization depends on the feature rather than how much it used
    it while fitting. Scored on average_precision because that is the metric
    we care about, and permutation importance is only meaningful relative to
    a metric.
    """
    result = permutation_importance(
        pipe, valid, valid["left_voluntarily_12m"],
        scoring="average_precision", n_repeats=n_repeats,
        random_state=seed, n_jobs=-1)
    return pd.DataFrame({
        "importance": result.importances_mean,
        "std": result.importances_std,
    }, index=valid.columns).sort_values("importance", ascending=False)


FEATURE_GROUPS = {
    "compensation": ["comp_ratio", "base_salary", "bonus_target_pct",
                     "unvested_equity_value", "last_raise_pct"],
    "raise_recency": ["months_since_raise"],
    "promotion_velocity": ["months_in_level", "level_overdue_ratio"],
    "tenure": ["tenure_months"],
    "manager": ["mgr_span", "months_with_manager", "team_manager_score"],
    "performance": ["rating_numeric", "rating_delta", "calibration_band"],
    "engagement": ["team_engagement_score", "team_response_rate"],
    "mobility": ["internal_applications_6m"],
    "role": ["level", "job_family", "org_l2", "location", "is_remote"],
    "controls": ["noise_highcard", "noise_binary"],
}


def grouped_permutation_importance(pipe: Pipeline, valid: pd.DataFrame,
                                   groups: dict = FEATURE_GROUPS,
                                   n_repeats: int = 30,
                                   seed: int = 7) -> pd.DataFrame:
    """Permute whole correlated groups together.

    This fixes the failure that single-feature permutation cannot. When
    `base_salary`, `comp_ratio`, and `band_midpoint` are correlated, shuffling
    any one of them leaves the model able to recover the signal from the other
    two, so each individually looks unimportant and the group as a whole looks
    unimportant, which is false. Shuffling the group jointly measures what the
    model would lose without compensation information at all.
    """
    rng = np.random.default_rng(seed)
    y = valid["left_voluntarily_12m"]
    base = average_precision_score(y, pipe.predict_proba(valid)[:, 1])

    rows = []
    for name, columns in groups.items():
        present = [c for c in columns if c in valid.columns]
        if not present:
            continue
        drops = []
        for _ in range(n_repeats):
            shuffled = valid.copy()
            order = rng.permutation(len(shuffled))
            # One shared permutation order across the group preserves the
            # within-group correlation structure while destroying its
            # relationship to the target.
            shuffled[present] = shuffled[present].to_numpy()[order]
            drops.append(base - average_precision_score(
                y, pipe.predict_proba(shuffled)[:, 1]))
        rows.append({"group": name, "importance": float(np.mean(drops)),
                     "std": float(np.std(drops)), "n_features": len(present)})
    return pd.DataFrame(rows).set_index("group").sort_values(
        "importance", ascending=False)

The three tables disagree, and the disagreement is the finding.

Comparison of impurity importance against held-out permutation importance for the same random forest, showing the injected high-cardinality noise column ranking fourth by impurity and last by permutation, and correlated compensation features splitting their importance
Feature Impurity rank Impurity Permutation rank Permutation (PR-AUC drop)
months_since_raise 1 0.094 1 0.0412
comp_ratio 2 0.081 6 0.0104
tenure_months 3 0.078 3 0.0198
noise_highcard 4 0.071 21 0.0003
base_salary 5 0.068 9 0.0061
level_overdue_ratio 6 0.061 2 0.0221
mgr_span 7 0.054 4 0.0164
internal_applications_6m 8 0.031 5 0.0147
team_manager_score 11 0.024 7 0.0092
noise_binary 19 0.008 22 0.0001
is_remote 17 0.011 20 0.0004

Three things to read out of that table.

A pure noise column ranks fourth by impurity importance. noise_highcard is rng.normal(size=n), generated after the fact, with no relationship to anything. It carries 0.071 of the impurity importance, above base_salary and above level_overdue_ratio. Permutation importance on held-out data puts it 21st with an effect of 0.0003, indistinguishable from zero. This is the Strobl result reproducing exactly: continuous features with many distinct values offer many candidate splits, and impurity importance rewards the opportunity rather than the outcome.

internal_applications_6m is badly undersold by impurity importance. It ranks 8th there and 5th by permutation, and the gap is a cardinality artifact in the other direction: it takes integer values from 0 to 4, so it offers at most four split points, and it is rarely chosen even though it is decisive when it is. Impurity importance systematically understates low-cardinality features for the same reason it overstates high-cardinality ones.

comp_ratio drops from 2nd to 6th, and this one is not a bias artifact. It is correlated with base_salary, band_midpoint, and last_raise_pct, so shuffling comp_ratio alone leaves the model able to reconstruct most of the signal from its correlates. Individual permutation importance answers “what if I lost this one column”, which is the wrong question when the columns are redundant. That is what grouped permutation is for:

Feature group Grouped permutation (PR-AUC drop) Features Actionable
compensation (all 5 together) 0.0518 5 yes
raise_recency 0.0412 1 yes
promotion_velocity 0.0294 2 yes
manager 0.0231 3 yes
tenure 0.0198 1 no
mobility 0.0147 1 partly
engagement 0.0103 2 yes
performance 0.0081 3 no
role 0.0044 5 no
controls 0.0004 2 n/a

Compensation as a group is the strongest driver at 0.0518, well above any single feature, which is invisible in both single-feature tables. The recommendation that goes to the People team is therefore about compensation and raise cadence, and it would not have been if anyone had read the impurity table, where the top five contains a random number generator.

Key Insight

The design decision that mattered most was injecting a noise column and leaving it in permanently. It costs one line, it changes no prediction, and it converts "is this importance number real" from a judgement call into a measurement: anything ranked at or below `noise_highcard` is indistinguishable from nothing. It found that the default importance table had noise in fourth place, which invalidated the compensation-versus-management conclusion the first version of this analysis reached. Every importance table shipped to a decision-maker should have a control row, for the same reason an assay has a blank.

Evaluation and Metrics

Precision at 200. The headline, matched to intervention capacity. Of the 200 highest-ranked employees, what share resign within 12 months.

Lift at 200. P@200 divided by the 14.8% base rate, which is the number that answers “is this better than picking names out of a hat” in a form a non-technical stakeholder can check.

PR-AUC, not ROC-AUC. At a 14.8% positive rate, ROC-AUC is inflated by the model’s ability to correctly rank the large negative majority, most of which nobody will ever look at. PR-AUC weights performance where the positives are.

Calibration in the top two deciles. If the tool tells a manager an employee is at 68% risk, the number needs to mean something, because managers calibrate their own effort against it. Overall calibration is beside the point since only the top of the ranking is used.

# Evaluation at the capacity the intervention actually has. Accuracy is
# reported last and only to show how uninformative it is.
import numpy as np
import pandas as pd
from sklearn.metrics import (average_precision_score, brier_score_loss,
                             roc_auc_score)


def precision_at_k(y_true, scores, k: int = 200) -> float:
    y_true = np.asarray(y_true)
    order = np.argsort(-np.asarray(scores), kind="stable")[:k]
    return float(y_true[order].mean())


def lift_at_k(y_true, scores, k: int = 200) -> float:
    base = float(np.asarray(y_true).mean())
    return precision_at_k(y_true, scores, k) / max(base, 1e-9)


def decile_calibration(y_true, scores, n_deciles: int = 10) -> pd.DataFrame:
    frame = pd.DataFrame({"y": np.asarray(y_true),
                          "p": np.asarray(scores, dtype=np.float64)})
    order = np.argsort(-frame["p"].to_numpy(), kind="stable")
    frame = frame.iloc[order].reset_index(drop=True)
    frame["decile"] = np.minimum(
        (np.arange(len(frame)) * n_deciles) // len(frame) + 1, n_deciles)
    out = frame.groupby("decile").agg(
        employees=("y", "size"),
        predicted_rate=("p", "mean"),
        observed_rate=("y", "mean"),
    )
    out["gap"] = out["predicted_rate"] - out["observed_rate"]
    return out


def evaluate_attrition(y_true, scores, k: int = 200) -> dict:
    y_true = np.asarray(y_true)
    scores = np.asarray(scores, dtype=np.float64)
    deciles = decile_calibration(y_true, scores)
    return {
        "precision_at_k": precision_at_k(y_true, scores, k),
        "lift_at_k": lift_at_k(y_true, scores, k),
        "pr_auc": float(average_precision_score(y_true, scores)),
        "roc_auc": float(roc_auc_score(y_true, scores)),
        "brier": float(brier_score_loss(y_true, scores)),
        "top2_decile_calibration_gap": float(
            deciles.loc[[1, 2], "gap"].abs().max()),
        "base_rate": float(y_true.mean()),
        "accuracy_at_half": float(((scores > 0.5) == (y_true == 1)).mean()),
        "majority_class_accuracy": float((y_true == 0).mean()),
        "deciles": deciles,
    }


def disparate_impact(flagged_ids, population: pd.DataFrame,
                     attribute: str) -> pd.DataFrame:
    """Four-fifths-rule check on the flagged set.

    Protected attributes are excluded from the FEATURES and required for the
    AUDIT. Commute distance proxies for neighborhood, which proxies for race
    in most cities, so an exclusion-only approach does not establish anything.
    Run this before any name leaves the model.
    """
    population = population.assign(
        flagged=population["employee_id"].isin(set(flagged_ids)))
    rates = population.groupby(attribute)["flagged"].agg(["size", "mean"])
    rates.columns = ["employees", "flag_rate"]
    rates["ratio_to_highest"] = rates["flag_rate"] / rates["flag_rate"].max()
    # Below 0.8 on the four-fifths rule is the conventional trigger for review.
    rates["below_four_fifths"] = rates["ratio_to_highest"] < 0.8
    return rates.sort_values("flag_rate", ascending=False)

Held-out final two quarters, 3,110 employee-quarters, 461 positives:

Metric HR heuristic Logistic (6 feat) Logistic (43 feat) Random forest RF, tuned leaf size
P@200 24.0% 29.5% 33.5% 38.0% 41.0%
Lift@200 1.62x 1.99x 2.26x 2.57x 2.77x
PR-AUC 0.211 0.243 0.318 0.381 0.402
ROC-AUC 0.612 0.681 0.744 0.771 0.814
Brier score n/a 0.121 0.117 0.109 0.104
Top-2-decile calibration gap n/a 0.14 0.11 0.19 0.06
Accuracy at 0.5 threshold 71.4% 79.8% 81.1% 83.9% 84.6%
Majority-class accuracy 85.2% 85.2% 85.2% 85.2% 85.2%

Read the last two rows together. Every model in the table has a worse accuracy than predicting that nobody leaves, and the best model is the second worst on accuracy. That is not a defect. Accuracy at a 0.5 threshold on a 14.8% positive rate rewards predicting the majority class, and a model that never flags anyone is worthless at the only task this project has. P@200 went from 24% to 41%, which is 82 of the 200 conversations landing on someone who would otherwise have left, against 48 under the incumbent heuristic.

The calibration row is worth noting too: the untuned forest is the worst calibrated model in the table at 0.19, worse than plain logistic regression, because deep trees with tiny leaves produce predictions clustered near 0 and 1. Raising min_samples_leaf to 12 fixed both accuracy and calibration at once, which is unusual and happens here because the same overfitting caused both.

Metric That Matters

Quarter-over-quarter Spearman correlation of the grouped importance table is the number that catches a silent regression, and it is not a prediction metric at all. P@200 is measured against labels that take 12 months to mature, so a degradation in ranking quality is invisible for a year. The importance table refreshes every quarter and its stability is observable immediately. When grouped importance rank correlation between consecutive quarters drops below about 0.8, something structural has changed: a reorg has scrambled the manager features, a comp band refresh has shifted every comp_ratio, or a new HRIS field is being populated inconsistently. In every case the ranking is degrading and the budget recommendation is about to change for a reason that has nothing to do with employee behaviour.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
Reading feature_importances_ as truth It is one attribute access and it returns a plausible-looking ranking Inject a high-cardinality noise column; if it lands in the top five, the table is unusable Use held-out permutation importance, keep the noise control permanently, and report the group version
Correlated features splitting importance Shuffling one of three redundant columns leaves the signal recoverable from the other two A feature group that is obviously important shows three mediocre individual scores Permute whole groups with a shared permutation order
Random row split on employee-quarters The rows look independent but one person contributes up to 8 of them Held-out ROC-AUC 0.887 under random split against 0.814 under grouped split Group by employee, and hold out the final quarters on top of that
Post-decision features Benefits declined, PTO zeroed, exit interview scheduled are recorded because someone is leaving Held-out ROC-AUC jumps above roughly 0.90, which is not achievable on pre-decision data Maintain a FORBIDDEN set asserted at featurization time
Retirements and involuntary exits in the label “Left the company” is the easy field to join on Age or level becomes a top feature; model does well on a population no intervention can help Exclude involuntary exits from the population and retirements from the label
Accuracy as the headline It is the default output of every tutorial The majority-class baseline beats every real model on it Report P@k at the intervention capacity, with PR-AUC as the threshold-free summary
Protected-attribute proxies Attributes are excluded but commute distance, university, and location encode them Four-fifths-rule ratio below 0.8 for any group in the flagged set Audit the flagged set on protected attributes even though the model never saw them
Acting on the model without a control group The intervention changes the label, so the model looks wrong when it works P@200 declines every quarter after launch with no model change Hold back a randomized control slice of the flagged set and measure the difference
Unstable importances across refits Deep trees with tiny leaves give high-variance importances Top five reorders between quarterly refits Raise min_samples_leaf, raise n_estimators, and report importance with its standard deviation
Common Pitfall

The mistake that does the most damage on this exact problem is treating a high importance score as a causal claim. `months_since_raise` is the top feature by every method here, and the natural next sentence is "so giving raises will reduce attrition". The model cannot support that. People who have not had a raise in a long time are also people whose managers have not advocated for them, who are in job families the company is deprioritizing, who have been passed over for a promotion, and who were already disengaged when the last cycle was decided. The feature is a marker for all of it. A 6 million dollar comp intervention justified by an importance score is a bet that the marker is the mechanism, and the honest version is to run it as an experiment: randomize the off-cycle adjustment within the flagged set and measure the difference in 12 month retention. That design costs one quarter of delay and is the only thing that distinguishes a 6 million dollar retention program from a 6 million dollar raise.

Scaling and Productionizing

The compute here is trivial. 94,300 rows and 800 trees train in 34 seconds on a laptop, and scoring 12,400 employees takes under two seconds. Every real production problem on this project is about data, governance, and the fact that the label takes a year to mature.

Quarterly refresh, measured:
  employee-quarters in training pool         91,200
  features after one-hot encoding               127
  RF fit, 800 trees, 8 cores                   34 s
  held-out permutation importance, 30 repeats  6.1 min
  grouped permutation importance, 30 repeats   2.4 min
  scoring the current 12,400 employees          1.8 s
  model artifact                              41 MB

Label maturity:
  snapshot to label close                   12 months
  newest fully-labeled snapshot cohort       Q3 2025
  cohorts in the rolling training window            8

The label delay means you cannot retrain your way out of a shift. The newest trainable snapshot is a year old, so a hiring surge, a layoff, or a labour market turn cannot be reflected in the model for four quarters. Two mitigations. Train on a rolling window of 8 snapshot cohorts so the model averages over several market conditions rather than memorizing one. And carry a 6 month companion label whose cohorts mature twice as fast, used purely as a divergence alarm: when the 6 month model’s top 200 overlaps the 12 month model’s by less than about 60%, something has changed that the slow model cannot yet see.

Governance is a harder constraint than accuracy. A list of names ranked by resignation probability is one of the most sensitive artifacts a company can produce. If a manager learns an employee is flagged, the risk of it becoming self-fulfilling is real, and if an employee learns they were passed over for a stretch project because a model flagged them, the company has a serious problem. The controls that matter: the People team sees aggregate importances and a flagged list, individual managers see a conversation prompt with no score, scores are never written into the HRIS where they could be joined to a performance record, and access is logged.

The self-fulfilling prophecy is a measurement problem with a standard fix. Once the People team acts on the list, the flagged employees’ outcomes are no longer a clean test of the model, and P@200 will appear to decline precisely when the program is working. Hold back a randomized 15% of the flagged set from intervention. That slice is small, it costs roughly 30 conversations a quarter, and it is the only way to separate “the model got worse” from “the intervention worked”. It also doubles as the experiment that turns the compensation correlation into a causal estimate.

The monitoring signal for silent degradation is the quarter-over-quarter rank correlation of the grouped importance table, checked against a 0.8 threshold at every refit. P@200 cannot serve this purpose because it lags by 12 months. Feature drift alone is too noisy on 43 columns during any reorg. The importance ranking is downstream of both the data and the model, refreshes immediately, and is the exact artifact whose stability the budget decision depends on.

Key Insight

Governance, not accuracy, is what makes this project hard to run for more than a year. Every other model in this section gets better as it gets more accurate. This one gets more dangerous: a more accurate list of names is a more consequential artifact in a domain where being on the list can change someone's career regardless of what they would have done. The teams that sustain an attrition model are the ones that decided early what managers see, what gets written down, and which slice is deliberately left alone, and none of those decisions is a modeling decision.

Real World

The methodological result this post is built around is Strobl, Boulesteix, Zeileis and Hothorn's Bias in random forest variable importance measures (BMC Bioinformatics, 2007), which demonstrated the cardinality bias in impurity importance and proposed conditional permutation importance as the fix; their `party` and `cforest` implementations in R still offer the conditional version that scikit-learn does not. Breiman's original 2001 random forest paper introduced permutation importance alongside the impurity version, so the better method has been available the entire time. On the applied side, the most instructive real-world case is a cautionary one: IBM publicly claimed a 95% accurate attrition predictor in 2019, a number that is difficult to interpret given that predicting nobody leaves scores in the high 80s at typical attrition rates, and the widely circulated "IBM HR Analytics Employee Attrition" Kaggle dataset is synthetic, which has not stopped it anchoring a great many published accuracy figures. Read any attrition accuracy claim against the base rate before anything else.

Alternative Approaches

Approach P@200 PR-AUC Training cost Interpretability Best fit
HR tenure and pay heuristic 24.0% 0.211 none Total The incumbent; a sanity check on anything more complex
Logistic regression, 43 features 33.5% 0.318 4 s High: signed coefficients, direct odds ratios When the deliverable is a defensible coefficient table and interactions are known to be weak
Random forest, tuned 41.0% 0.402 34 s Medium: permutation importance, SHAP The default here: interactions for free, OOB estimates, stable importances at this sample size
Gradient boosting (LightGBM) 42.1% 0.414 51 s Medium: SHAP over 127 columns When a point of precision matters more than importance stability
Cox proportional hazards 39.2% 0.388 22 s High: hazard ratios per covariate When the question is “when will they leave” rather than “who will leave in 12 months”
Neural network (3 layer MLP) 34.8% 0.331 6 min Low Nothing at this sample size; included as the cautionary row

For this problem I would ship the tuned random forest, and the 1.1 points of P@200 that LightGBM wins by is not enough to change that. The deciding factor is importance stability: measured across 8 quarterly refits, the forest’s grouped importance rank correlation averaged 0.87 and LightGBM’s averaged 0.71, because boosted trees fit residuals sequentially and a small change in the data reorders which features get used early. When the importance table is allocating an annual budget and has to survive a conversation with a CFO who remembers last quarter’s version, 0.87 against 0.71 matters more than 1.1 points of precision. The forest’s out-of-bag estimates are also a genuine convenience at 1,830 positive events, where every row held back for validation is a row not learned from.

The MLP row is there as a warning. Six minutes of training and 34.8% P@200, worse than logistic regression on the same features, is what 1,830 positive events across 127 columns buys you. Sample size, not model sophistication, is the binding constraint.

I would switch under two conditions. If the question changes from “who will leave in the next 12 months” to “how long until this person leaves”, the Cox model becomes the right tool rather than a slightly worse one, because it uses the timing information the binary label throws away and handles censoring properly, which matters for the 41% of the population with under 24 months of tenure. And if the company grows past roughly 50,000 employees, the sample size constraint relaxes, gradient boosting’s accuracy advantage grows, the importance instability shrinks because each refit sees more data, and the tradeoff reverses.

Key Takeaways

  • The importance table is a deliverable, so validate it like one. It decides a budget. Validating the classifier and then reading feature_importances_ uncritically validates the wrong half of the output.
  • Inject a noise control and keep it. One line of code. On this data a high-cardinality noise column ranked fourth by impurity importance and 21st by held-out permutation importance. Anything at or below the control is indistinguishable from nothing.
  • Impurity importance is biased by cardinality in both directions. It overstated a random continuous column and understated internal_applications_6m, which takes five distinct values and is genuinely predictive. Strobl et al. (2007) documented this and the fix has existed since Breiman’s 2001 paper.
  • Permute correlated features as groups. Compensation as a group scored 0.0518 while its strongest single member scored 0.0104. Single-feature permutation asks “what if I lost this column”, which is the wrong question when the columns are redundant.
  • Group the split by employee. One person contributes up to 8 near-identical snapshots. A random split reads 0.887 ROC-AUC against a true 0.814, and the model is recognizing individuals rather than predicting behaviour.
  • Accuracy is worse than useless here. Predicting that nobody leaves scores 85.2%, beating every real model in the comparison table. Report precision at the intervention capacity.
  • Match the metric to the capacity. The People team runs 200 conversations a quarter, so P@200 is the metric. Model quality at any other operating point is not actionable.
  • Importance is not causation. months_since_raise is a marker for manager advocacy, promotion decisions, and prior disengagement all at once. Turning it into a 6 million dollar comp program without randomizing is a bet, not an inference.
  • Governance is the long-run constraint. A ranked list of names is a consequential artifact, and a more accurate one is more consequential. Decide what managers see and which slice goes un-intervened before the first list ships.

The counter-intuitive lesson is that the most valuable output of this project was a negative result about the tooling rather than anything about employees. The first version of this analysis concluded, from the default importance table, that manager quality and compensation were comparable drivers, and recommended splitting the budget. Adding one noise column and switching to held-out grouped permutation importance changed that: compensation and raise cadence together were roughly twice the manager group, and one of the features supporting the original split was a random number generator. The model’s ranking quality barely moved between those two versions, and the recommendation moved by millions of dollars. When the explanation is the product, the estimator that produces the explanation deserves as much scrutiny as the one that produces the predictions, and it almost never gets it.

Frequently Asked Questions

Q: Why not just use SHAP, which handles feature attribution properly and is what everyone uses now?

A: SHAP is a good addition and it does not replace what grouped permutation importance does here. TreeSHAP gives exact, locally accurate per-employee attributions, which is genuinely useful for the conversation prompt a manager sees. Its aggregate version has the same redundancy problem as single-feature permutation: Shapley values split credit among correlated features, so compensation still appears as five mediocre contributors rather than one strong group. SHAP also attributes what the model does, including where the model is overfitting, whereas held-out permutation measures what the model’s generalization actually depends on. Use both: SHAP for the individual view, grouped permutation for the budget view.

Q: Why not gradient boosting, which scored 1.1 points higher on P@200?

A: Importance stability. Across 8 quarterly refits the forest’s grouped importance rank correlation averaged 0.87 and LightGBM’s 0.71, because boosting fits residuals sequentially and small data changes reorder which features get used early. The importance table is allocating an annual budget and has to survive being compared to last quarter’s version in front of a CFO. If the deliverable were only the ranked list of 200 names, I would ship the boosted model.

Q: Why PR-AUC and P@200 rather than ROC-AUC?

A: At a 14.8% positive rate, ROC-AUC is substantially driven by correctly ranking the negative majority, and only the top 1.6% of the ranking will ever be looked at. PR-AUC weights the region where the positives are, and P@200 measures exactly the operating point the intervention capacity fixes. The practical demonstration is in the results table: ROC-AUC moved 0.771 to 0.814 between the two forests while P@200 moved 38% to 41%, and the second is the number that translates into conversations that land.

Q: Is excluding protected attributes enough to make this fair?

A: No, and treating it as sufficient is the common error. Commute distance proxies for neighborhood, which proxies for race in most cities; university proxies for socioeconomic background; team assignment often proxies for several things at once. Exclusion prevents the model from using an attribute directly and does nothing about correlated features reconstructing it. The protected attributes are therefore excluded from the features and required for the audit: run the four-fifths-rule check in disparate_impact on the flagged set before any name leaves the model, and investigate the responsible feature when a group falls below 0.8.

Q: How do you evaluate the model once the People team starts acting on it?

A: Hold back a randomized 15% of the flagged set from intervention. Without it, successful retention makes the model look wrong, and P@200 declines every quarter for the best possible reason. The control slice is about 30 employees a quarter, which is small enough to be affordable and large enough to accumulate into a usable estimate over four or five quarters. It also doubles as the experiment that converts the compensation correlation into a causal effect estimate.

Q: What breaks first in production?

A: A reorg. It scrambles mgr_span, months_with_manager, and org_l2 for thousands of employees at once, and it does so in a way that looks like a behavioural change rather than a structural one. The grouped importance rank correlation drops below 0.8 in the same quarter, which is the alarm. The specific trap is the HRIS manager_id field being corrected retroactively, so a historical snapshot rebuilt after the reorg shows the new manager and the model appears to have been predicting from information that did not exist. Snapshots must come from an as-of view or a change log.

Interview Questions

Q: You fit a random forest, read feature_importances_, and the top feature is a continuous variable. How much do you trust that, and how would you check?

Expected depth: Name mean decrease in impurity and its cardinality bias: features with many distinct values offer many candidate split points and get more chances to reduce impurity on a bootstrap sample, so the measure conflates predictiveness with opportunity. Cite Strobl et al. (2007). The check is a noise control: inject a high-cardinality random column and see where it ranks. Then propose held-out permutation importance as the replacement and explain why held-out matters, since impurity importance is computed on training data and therefore rewards overfitting. Strong answers add that the bias runs both ways and that low-cardinality features are systematically understated.

Q: Your compensation features are correlated. Permutation importance says each of them is unimportant. Is compensation unimportant?

Expected depth: No, and the reasoning is the point. Single-feature permutation asks what happens if this one column is destroyed, and with redundant columns the model reconstructs the signal from the survivors, so each looks individually dispensable while the group is essential. The fix is to permute the group jointly with a shared permutation order, which preserves the within-group correlation structure while destroying its relationship to the target. Mentioning Strobl’s conditional permutation importance, or clustering features by correlation before grouping, marks a strong answer. Noting that Shapley values have the same credit-splitting issue is better still.

Q: Your model reports 85% accuracy on attrition prediction. Interpret that.

Expected depth: Immediately compare to the base rate: at 14.8% attrition, predicting that nobody leaves scores 85.2%, so 85% accuracy is at or below the no-information floor. Then move to the right framing: the intervention capacity is fixed at 200 conversations a quarter, so the metric is precision at 200 with lift against the base rate, and PR-AUC as the threshold-free summary. Top answers note that every model in a realistic comparison table has worse 0.5-threshold accuracy than the majority-class baseline and that this is expected, not a defect.

Q: You have 12,400 employees observed over 8 quarterly snapshots. Design the train-test split and name what leaks if you get it wrong.

Expected depth: Two separations doing two jobs: group by employee so no individual appears on both sides, and hold out the final quarters as a time boundary. The leak from the missing group constraint is individual memorization, since features barely move quarter to quarter and an individual’s label is constant across their snapshots, which inflates held-out ROC-AUC from roughly 0.814 to 0.887. Raise post-decision feature leakage unprompted (benefits declined, PTO zeroed, exit interview scheduled) and survivorship in the snapshot population. Noting that employees in the test quarters must be removed from training entirely, not just from those quarters, is the detail that separates a good answer from a complete one.

Q: months_since_raise is your top feature by every importance method. The CFO asks whether a 6 million dollar off-cycle comp adjustment will reduce attrition. What do you say?

Expected depth: Separate prediction from causation explicitly. The feature is a marker that bundles manager advocacy, promotion decisions, job-family prioritization, and prior disengagement, and a high importance score establishes predictive association under the current policy regime, not the effect of intervening. Note that acting on the feature changes the data-generating process, so the observed relationship need not survive the intervention. Propose the experiment: randomize the adjustment within the flagged set, hold back a control slice, and measure the 12 month retention difference. A strong answer also mentions that the randomized holdback is needed anyway to evaluate the model once the People team starts intervening, so the experiment is nearly free.

View full code for this problem