Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 9 of 10
Which Features Matter? Feature Importances, Permutation Importance and SHAP
Ask a tuned rain model why. Tree importances show what the trees used, permutation importance shows what the score needs (shuffling Humidity3pm drops F1 from 0.637 to 0.453), and SHAP explains one day the model is 97% sure will rain.
What you will learn
- Read a tree model's feature_importances_ and know what they leave out
- Shuffle one column by hand and measure the score drop
- Rank every original column with permutation_importance on the test set
- Explain one single prediction, push by push, with SHAP
Before you start
- Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
- Pipelines and ColumnTransformer
Picture a football coach reviewing a match. One way to judge the players is to ask who ran the most. Wind ran 11 kilometres, so Wind must be the star? Not really. Busy isn't the same as useful.
A better review: bench one player and replay the match. Without Humidity, the score goes from 3-1 to 1-1. The team got much worse, so Humidity really mattered.
The players are your features, and the match is your model's score. This article shows three ways to review them: what the trees used, what the score needs, and who pushed one answer. We'll ask the tuned rain model from Hyperparameter Tuning why it says what it says.
The model and one day to explain
Same 20,000 days of Rain in Australia, same split and same two-lane pipeline. The XGBoost settings are the ones random search picked. You'll need pip install shap for the last part.
import warnings
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.inspection import permutation_importance
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from xgboost import XGBClassifier
warnings.filterwarnings("ignore")
df = pd.read_csv("weatherAUS.csv").dropna(subset=["RainTomorrow"])
df = df.sample(20_000, random_state=42)
X = df.drop(columns=["Date", "RISK_MM", "RainTomorrow"])
y = (df["RainTomorrow"] == "Yes").astype(int)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
num = X.select_dtypes(include="number").columns
cat = X.select_dtypes(exclude="number").columns
num_steps = Pipeline([("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())])
cat_steps = Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore"))])
preprocess = ColumnTransformer([("num", num_steps, num),
("cat", cat_steps, cat)])
xgb = XGBClassifier(n_estimators=400, max_depth=7, learning_rate=0.03,
scale_pos_weight=3, random_state=42)
model = Pipeline([("preprocess", preprocess), ("clf", xgb)])
model.fit(X_train, y_train)
print("test F1:", round(f1_score(y_test, model.predict(X_test)), 3))
test F1: 0.637
Now pick one test day, number 17, and ask for the chance of rain:
i = 17
day = X_test.iloc[[i]]
cols = ["Location", "Humidity3pm",
"Sunshine", "RainToday"]
print(day[cols].to_string(index=False))
p = model.predict_proba(day)[0, 1]
print("P(rain):", round(p, 2))
Location Humidity3pm Sunshine RainToday
Moree 94.0 0.0 Yes
P(rain): 0.97
Moree, 94% humidity in the afternoon, no sunshine, and it rained today. The model is 97% sure it will rain tomorrow. But which columns made it so sure?
Tree feature_importances_: who ran the most
Tree models keep a score for every input column for free. model[-1] is the XGBoost step and model[:-1] is everything before it, which gives us the column names after one-hot encoding.
steps = model[:-1]
names = [n.split("__")[1]
for n in steps.get_feature_names_out()]
imp = model[-1].feature_importances_
tree_imp = pd.Series(imp, index=names)
top = tree_imp.sort_values(ascending=False)
print(top.head(5).round(3).to_string())
Humidity3pm 0.062
Sunshine 0.022
Pressure3pm 0.018
WindGustSpeed 0.018
WindDir3pm_NW 0.015
split("__")[1] drops the num__ / cat__ prefix the ColumnTransformer adds. Humidity3pm is on top, then Sunshine, Pressure3pm and WindGustSpeed.
Two limits. These numbers only say how much the trees used a column, not how much the score depends on it. And a one-hot piece like WindDir3pm_NW (north-west wind at 3pm) appears on its own, so one original column is spread over many rows. This is the player who ran the most.
Bench a player: shuffle one column
Now the replay. Take the test rows, shuffle only the Humidity3pm column so each day gets another day's humidity, and score again. Every other column stays as it was.
base = f1_score(y_test, model.predict(X_test))
shuffled = X_test.copy()
mixed = shuffled["Humidity3pm"].sample(frac=1, random_state=42)
shuffled["Humidity3pm"] = mixed.values
drop = f1_score(y_test, model.predict(shuffled))
print("F1 normal: ", round(base, 3))
print("F1 shuffled:", round(drop, 3))
F1 normal: 0.637
F1 shuffled: 0.453
What did the shuffle do to the first four test days?
rows = pd.DataFrame({"before": X_test["Humidity3pm"].values[:4],
"after": shuffled["Humidity3pm"].values[:4]})
print(rows.to_string(index=False))
before after
6.0 36.0
80.0 14.0
46.0 52.0
51.0 48.0
The second day had 80% humidity and now gets 14%. With humidity scrambled, F1 falls from 0.637 to 0.453. A big drop means the model really needs that column. That drop is the permutation importance of Humidity3pm. .values matters here: without it pandas would line the shuffled values back up by index and undo the shuffle.
permutation_importance for every column
scikit-learn repeats this for every column. Give it the whole pipeline, the test rows and a score. n_repeats=5 shuffles each column five times and keeps the average drop, so one lucky shuffle doesn't decide.
result = permutation_importance(
model, X_test, y_test,
scoring="f1", n_repeats=5,
random_state=42)
imp = result.importances_mean
perm = pd.Series(imp, index=X_test.columns)
top = perm.sort_values(ascending=False)
print(top.head(5).round(3).to_string())
Humidity3pm 0.178
Pressure3pm 0.073
WindGustSpeed 0.062
Sunshine 0.031
Rainfall 0.015
Because we passed the whole pipeline and the raw X_test, it shuffles the original 21 columns, before any one-hot encoding. And it only needs predict and a score, so it works for any model, not just trees.
Two lists, one model
The tree list counts how much a column was used inside the trees. The permutation list asks what the score would lose without it. When you want to know what the model really depends on, trust the second one more.
SHAP: who pushed this one answer?
Permutation importance explains the model as a whole. But our question was about one day: why 97% rain for Moree? For that we use SHAP. It splits one prediction into one push per column. Positive pushes towards rain, negative pushes away.
TreeExplainer works on the XGBoost step itself, so we first transform the test rows with the preprocessing steps:
import shap
X_test_t = model[:-1].transform(X_test)
explainer = shap.TreeExplainer(model[-1])
sv = explainer(X_test_t)
push = pd.Series(sv.values[i], index=names)
top = push.sort_values(key=abs, ascending=False).head(5)
print(top.round(2).to_string())
Humidity3pm 3.39
Sunshine 0.63
WindDir3pm_SSE -0.42
Cloud3pm 0.38
Evaporation -0.36
sort_values(key=abs) ranks by size, whatever the sign. For day 17, the 94% humidity pushes hard towards rain, +3.39. Zero sunshine adds +0.63. A south-south-east wind at 3pm pulls the other way, -0.42. These pushes are in the model's raw score units (log-odds for XGBoost), not percentages, so compare them with each other rather than reading them as chances.
SHAP can also show every test day at once. Each dot below is one day, placed by how hard that column pushed, and coloured by the column's value (red high, blue low):

This plot adds what the two lists couldn't: direction. High humidity means rain, but high pressure and lots of sunshine mean dry.
Three tools, three questions
| Tool | Question it answers | Works on | One day? |
|---|---|---|---|
feature_importances_ | Which columns did the trees use? | tree models only | no |
permutation_importance | Which columns does the score need? | any model | no |
| SHAP | Who pushed this answer, and which way? | TreeExplainer for trees; other explainers exist | yes |
Why bother? A loan is refused, a rain warning goes out, and someone asks why. Now you can answer. They also help you spot a column that shouldn't be there at all. If one column towers over all the others, ask whether you'd really know its value at prediction time, the question behind the RISK_MM leak in Train-Test Split and Data Leakage. Choosing which columns to keep before training is a separate job, covered in Feature Selection.
Common mistakes
- Treating
feature_importances_as the truth. It shows use, not need, and it splits one-hot columns into pieces. - Running permutation importance on the training rows. A model that memorised noise looks like it needs that noise. Use the test (or validation) rows.
- Reading importance as cause. Humidity predicts rain in this model; the tools explain the model, not the weather.
- Forgetting the preprocessing for SHAP.
TreeExplainergets the XGBoost step, so it needs the transformed rows and the transformed names.
Quick recap
| Step | Rain model result |
|---|---|
One day, predict_proba | Moree, P(rain) 0.97 |
| Tree importances, top | Humidity3pm 0.062 |
| Shuffle Humidity3pm by hand | F1 0.637 to 0.453 |
| Permutation importance, top | Humidity3pm 0.178, Pressure3pm 0.073 |
| SHAP, day 17 | Humidity3pm +3.39, Sunshine +0.63 |
Try it yourself
Run permutation_importance with scoring="recall" instead of F1. Does the top five change?
The notebook and weatherAUS.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
Next →Project: The Classification Master Template, from Raw CSV to a Saved Model
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.