Sub topic 1
Why Look Inside a Trained Model
Prerequisites
This chapter assumes you can train and evaluate a supervised model with a train/test split. You should know basic Python with NumPy and pandas, and the scikit-learn estimator interface (fit, predict, score). You should also know a common metric such as R² or accuracy.
Why inspect a model at all
A score such as R² = 0.80 tells you how well a 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 be using a feature that will not exist in production.
Inspecting a trained model helps you with several practical jobs:
- Debugging. Find features that leak the target, or that dominate for the wrong reason.
- Validation. Check that the model's behavior agrees with domain knowledge. If predicted house prices fall as income rises, something is wrong.
- Feature selection. Identify features that add nothing and can be dropped.
- Communication. Give stakeholders a defensible account of what drives predictions.
Global and local explanations
Explanations come in two scopes.
| Scope | Question it answers | Example |
|---|---|---|
| Global | How does the model behave across the whole dataset? | Which features matter most overall? |
| Local | Why did the model make this one prediction? | Why was this loan applicant scored as high risk? |
This tutorial focuses on global explanations. Local tools such as ICE curves appear later, as a way to see the individual rows behind a global average.
Model-internal and model-agnostic methods
A second distinction is how the method gets its answer.
A model-internal measure reads the fitted model's own structure. The feature_importances_ attribute of a random forest is an example. It sums how much each feature reduced impurity across the trees' splits. It exists only for tree models, and it is computed from the training data.
A model-agnostic method treats the model as a black box. It changes the inputs, calls predict, and watches what happens to the output. Because it needs only predict (and a score), it works on a random forest, a gradient-boosted model, a neural network, or a pipeline in the same way.
This tutorial covers two model-agnostic methods:
- Permutation importance shuffles one feature at a time on held-out data and measures how much the score drops. It ranks features.
- Partial dependence sets a feature to a range of values and averages the predictions. It shows the direction and shape of an average effect.
The two answer different questions, so they are often used together. Importance tells you which features to look at. Dependence tells you what those features do.
A first look at the data
The examples in this tutorial use the California housing data. The target is the median house value for a district, and the features describe the district, such as median income (MedInc) and average occupancy (AveOccup). The code below loads the data and sets up a held-out split.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
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)
print(f"Test R^2: {model.score(X_test, y_test):.3f}")A single number summarizes the model. The next chapters open it up.
Exercise
A colleague says, "Our random forest's feature_importances_ is model-agnostic, so we can use it to compare a forest and a neural network." What is wrong with this claim?
Show answer
feature_importances_ is model-internal. It is computed from impurity reductions in the tree splits, so it exists only for tree-based models and cannot be compared with a neural network. A model-agnostic method such as permutation importance needs only predict and a score, so it can be applied to both models.