Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathChoose and Tune a Model: Classic Algorithms to a Saved Pipeline
  1. 1
    K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
  2. 2
    Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
  3. 3
    Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
  4. 4
    Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
  5. 5
    Bagging and Random Forest: Many Shaky Trees, One Steady Answer
  6. 6
    Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
  7. 7
    Voting and Stacking: Does a Team of Models Beat the Best One?
  8. 8
    Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
  9. 9
    Which Features Matter? Feature Importances, Permutation Importance and SHAP
  10. 10
    Project: The Classification Master Template, from Raw CSV to a Saved Model
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

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.

Chaand Sheikh

·27 November 2026Model Selection and Tuning

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

Tree importances against permutation importance What the trees used feature_importances_ What the score needs permutation_importance, F1 drop 1. Humidity3pm0.062 2. Sunshine0.022 3. Pressure3pm0.018 4. WindGustSpeed0.018 5. WindDir3pm_NW (one-hot)0.015 1. Humidity3pm0.178 2. Pressure3pm0.073 3. WindGustSpeed0.062 4. Sunshine0.031 5. Rainfall (new)0.015
Humidity is first in both. Pressure and wind gust move up a place, Sunshine drops two, the one-hot wind piece disappears and Rainfall appears. The two lists measure different things.

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 pushes for one day Day 17, Moree: P(rain) 0.97 away from rain towards rain Humidity3pm+3.39 Sunshine+0.63 WindDir3pm_SSE-0.42 Cloud3pm+0.38 Evaporation-0.36
The five biggest SHAP values for one test day, drawn to scale from the notebook output. Humidity does most of the work.

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):

SHAP summary plot for the test days. Rows from top: Humidity3pm, Pressure3pm, WindGustSpeed, Sunshine, Cloud3pm, Rainfall, Pressure9am, then the sum of 108 other features. For Humidity3pm, high values (red) sit far to the right, up to about +4, and low values (blue) sit to the left. For Pressure3pm and Sunshine the pattern is reversed: high values push left, away from rain.
SHAP summary for the test days. High humidity pushes towards rain; high afternoon pressure and lots of sunshine push away from it.

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

ToolQuestion it answersWorks onOne day?
feature_importances_Which columns did the trees use?tree models onlyno
permutation_importanceWhich columns does the score need?any modelno
SHAPWho pushed this answer, and which way?TreeExplainer for trees; other explainers existyes

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. TreeExplainer gets the XGBoost step, so it needs the transformed rows and the transformed names.

Quick recap

StepRain model result
One day, predict_probaMoree, P(rain) 0.97
Tree importances, topHumidity3pm 0.062
Shuffle Humidity3pm by handF1 0.637 to 0.453
Permutation importance, topHumidity3pm 0.178, Pressure3pm 0.073
SHAP, day 17Humidity3pm +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 →
← Previous
Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
Next →
Project: The Classification Master Template, from Raw CSV to a Saved Model
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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.

On this page
  • The model and one day to explain
  • Tree feature_importances_: who ran the most
  • Bench a player: shuffle one column
  • permutation_importance for every column
  • Two lists, one model
  • SHAP: who pushed this one answer?
  • Three tools, three questions
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.