Sub topic 1
Why Look Inside a Trained Model
A trained model gives you predictions, but a prediction alone does not tell you why the model made it. This chapter explains what model inspection is for, how global and local explanations differ, and why this tutorial focuses on two model-agnostic tools: permutation importance and partial dependence. The later chapters build and use those tools.
Prerequisites
This chapter assumes you can do the following:
- Train and evaluate a supervised model with a train/test split.
- Write basic Python with NumPy and pandas.
- Use scikit-learn estimators through
fit,predict, andscore. - Read common metrics such as R² for regression or accuracy for classification.
You do not need any prior knowledge of interpretability methods.
Why a good score is not enough
A single test score, such as an R² of 0.81, tells you how well the model predicts. It does not tell you what the model relies on. Two models with the same score can use very different features, and one of them may rely on something you would not trust.
People inspect trained models for several practical reasons:
- Debugging. A feature that matters far more than expected can signal a data leak. For example, an ID column or a field recorded after the outcome can inflate performance.
- Validation against domain knowledge. If a house price model predicts lower prices as income rises, something is wrong with the data or the model.
- Feature selection. Features that contribute nothing can be dropped to simplify the pipeline.
- Communication. Stakeholders often need a plain statement of what drives the predictions before they will use them.
- Fairness and compliance. Reviewers may need evidence that a model does not depend heavily on a sensitive attribute or a close proxy for it.
Inspection does not prove that a model is correct. It gives you evidence about its behavior, and that evidence has its own limits, which later chapters cover.
Global and local explanations
Explanation methods answer questions at two different scales.
- A global explanation describes the model's behavior across the whole dataset. An example is "median income is the most important feature overall."
- A local explanation describes one prediction. An example is "this house was predicted to be expensive mainly because of its location."
This tutorial is mostly about global explanations. Permutation importance ranks features over a whole dataset. Partial dependence shows an average effect over a whole dataset. Individual conditional expectation (ICE) curves, covered later, sit between the two. They show one curve per row, so they let you move from the global view toward the local one.
| Question | Scale | Example method |
|---|---|---|
| Which features matter most overall? | Global | Permutation importance |
| How does the average prediction change as a feature changes? | Global | Partial dependence |
| How does the prediction for this one row change? | Local | ICE curve, SHAP values |
Model-internal and model-agnostic methods
Methods for inspecting a model fall into two groups.
Model-internal methods read the model's own structure. A linear model has coefficients. A decision tree has split rules. A random forest in scikit-learn exposes feature_importances_, which measures how much each feature reduced impurity across the trees' splits. These measures are cheap because they come for free with training. They only exist for certain model families, and each one has its own meaning, so you cannot compare them across model types.
Model-agnostic methods treat the model as a black box. They only call predict (or score) with modified inputs and watch what happens to the output. Because they never look at the model's internals, the same code works for a random forest, a gradient-boosted ensemble, a neural network, or a support vector machine.
The two methods in this tutorial are model-agnostic:
- Permutation importance shuffles one feature at a time and measures how much the model's score drops.
- Partial dependence sets one feature to a series of values for every row and measures how the average prediction changes.
Both are experiments on the model. You change the input, run the model, and compare outputs.
What the two methods report
It helps to see the shape of each result before learning how it is computed.
Permutation importance returns one number per feature. The number is the average drop in the model's score when that feature's values are shuffled. A large drop means the model depends on the feature. A drop near zero means that shuffling the feature does not hurt the score.
Partial dependence returns a curve per feature, or a surface for a pair of features. The horizontal axis is the feature's value. The vertical axis is the average prediction. The curve shows direction (rising or falling), shape (linear, flat, or stepped), and strength (how far the curve moves).
These two views answer different questions, so they are most useful together. Importance tells you where to look. Dependence tells you what the model does with that feature.
A preview of the code
You will build both methods in later chapters. The following snippet shows how little code the scikit-learn version needs. It trains a random forest on the California housing data, then reports permutation importance on the held-out split.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(as_frame=True, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=0)
model.fit(X_train, y_train)
result = permutation_importance(
model, X_test, y_test, n_repeats=10, random_state=0, n_jobs=-1
)
for i in result.importances_mean.argsort()[::-1]:
print(f"{X.columns[i]:<12} {result.importances_mean[i]:.3f} +/- {result.importances_std[i]:.3f}")Read the code in four parts:
- The data is split once, and the model is fitted only on the training part.
permutation_importancereceives the fitted model and the held-out data. It never refits the model.n_repeats=10shuffles each feature ten times, so you get a mean and a standard deviation instead of a single noisy number.- The loop sorts features from most to least important and prints each mean with its spread.
The output is a ranked list with one row per feature. You do not need to interpret it yet. The point here is the workflow: fit once, then probe the fitted model from the outside.
What these methods cannot do
Before using any inspection tool, keep its limits in mind.
- They describe the model, not the world. If permutation importance says a feature matters, the model uses that feature. It does not show that changing the feature in reality would change the outcome. Causal claims need other evidence.
- They depend on the data you give them. Results computed on training data can differ from results on held-out data. A later chapter covers this difference.
- They struggle with correlated features. When two features carry the same information, shuffling one can look harmless because the other covers for it. Partial dependence also builds input rows that may never occur in real data.
- Averages hide detail. A flat partial dependence curve can come from two opposite effects that cancel out.
Each of these points gets its own chapter. Knowing them now helps you treat the outputs as evidence to check, not as final answers.
How the rest of the tutorial is organized
The chapters follow a path from setup to workflow:
- Set up a held-out split and a score to track.
- See why built-in tree importances are not enough.
- Build permutation importance, then compare training and test results and study correlated features.
- Build partial dependence, read one-way and two-way plots, and add ICE curves.
- Learn where partial dependence misleads, and meet alternatives such as conditional permutation, ALE, and SHAP.
- Combine the tools into a workflow: rank features first, then probe the important ones.
Exercise
A teammate says, "The random forest's built-in featureimportances and a permutation importance computation are both feature importance, so they are interchangeable." Give two differences that show why this is wrong, and say which one is model-agnostic.
Show answer
The built-in importance is model-internal. It is derived from how much each feature reduced impurity in the trees' splits during training, so it exists only for certain model families and is computed from training data. Permutation importance is model-agnostic. It only needs a fitted model and a scoring function, it works with any estimator, and it can be computed on held-out data by measuring the drop in score after shuffling a feature. The two can rank features differently, so they are not interchangeable.
Exercise
You plot a partial dependence curve for a feature and it is almost flat. A colleague concludes the model ignores that feature. Name one reason this conclusion might be wrong, and name a tool from this chapter that could help check it.
Show answer
The curve averages over all rows, so two opposite effects can cancel. For example, the prediction may rise with the feature for some rows and fall for others, and the average stays flat. ICE curves show one line per row and would reveal this. Permutation importance on held-out data is another check, since a feature the model uses should produce a score drop when shuffled.