Bird
Raised Fist0
ML Pythonml~20 mins

Model interpretability (SHAP, LIME) in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Model interpretability (SHAP, LIME)
Problem:You have trained a classification model on the Iris dataset. The model achieves good accuracy, but you want to understand which features influence its predictions the most.
Current Metrics:Training accuracy: 95%, Validation accuracy: 93%
Issue:The model works well but is a 'black box'. You cannot explain why it makes certain predictions.
Your Task
Use SHAP and LIME to explain the model's predictions and identify the most important features influencing the output.
Use the existing trained model without changing its architecture or training process.
Use SHAP and LIME libraries for interpretability.
Explain at least one prediction with each method.
Hint 1
Hint 2
Hint 3
Solution
ML Python
import numpy as np
import shap
import lime
import lime.lime_tabular
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt

# Load data
iris = load_iris()
X, y = iris.data, iris.target
feature_names = iris.feature_names

# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train model
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)

# SHAP explanation
explainer_shap = shap.TreeExplainer(model)
shap_values = explainer_shap.shap_values(X_test)

# Plot SHAP summary for class 0
shap.summary_plot(shap_values[0], X_test, feature_names=feature_names, show=False)
plt.title('SHAP Summary Plot for Class 0')
plt.tight_layout()
plt.savefig('shap_summary.png')
plt.close()

# Explain one prediction with SHAP
idx = 0
shap.force_plot(explainer_shap.expected_value[0], shap_values[0][idx], X_test[idx], feature_names=feature_names, matplotlib=True, show=False)
plt.title('SHAP Force Plot for One Prediction')
plt.tight_layout()
plt.savefig('shap_force_plot.png')
plt.close()

# LIME explanation
explainer_lime = lime.lime_tabular.LimeTabularExplainer(X_train, feature_names=feature_names, class_names=iris.target_names, discretize_continuous=True)

exp = explainer_lime.explain_instance(X_test[idx], model.predict_proba, num_features=4)

# Show LIME explanation as list
lime_exp_list = exp.as_list()

# Plot LIME explanation
fig = exp.as_pyplot_figure()
plt.title('LIME Explanation for One Prediction')
plt.tight_layout()
plt.savefig('lime_explanation.png')
plt.close()

# Output results
print(f"LIME explanation for test instance {idx}:")
for feature, weight in lime_exp_list:
    print(f"{feature}: {weight:.3f}")
Added SHAP TreeExplainer to explain feature importance globally and for one prediction.
Added LIME TabularExplainer to explain one prediction locally.
Visualized SHAP summary plot and force plot for interpretability.
Visualized LIME explanation plot and printed feature contributions.
Results Interpretation

Before: Model accuracy was high but no insight into feature influence.

After: SHAP and LIME provide clear visual and numeric explanations showing which features most affect predictions.

Using SHAP and LIME helps us open the 'black box' of machine learning models. We can see which features matter most and understand individual predictions better.
Bonus Experiment
Try using SHAP and LIME to explain predictions on a different dataset, such as the Breast Cancer dataset.
💡 Hint
Load the new dataset from sklearn, train a similar model, and apply the same SHAP and LIME methods to interpret it.

Practice

(1/5)
1. What is the main purpose of using SHAP or LIME in machine learning?
easy
A. To improve the speed of model training
B. To reduce the number of features in the dataset
C. To increase the size of the training dataset
D. To explain why a model made a specific prediction

Solution

  1. Step 1: Understand model interpretability tools

    SHAP and LIME are designed to explain model predictions by showing feature importance.
  2. Step 2: Identify their main use

    They help users understand why a model made a certain prediction, increasing trust.
  3. Final Answer:

    To explain why a model made a specific prediction -> Option D
  4. Quick Check:

    Interpretability = Explanation [OK]
Hint: SHAP and LIME explain predictions, not speed or data size [OK]
Common Mistakes:
  • Confusing interpretability with model training speed
  • Thinking SHAP/LIME reduce dataset size
  • Assuming they automatically improve model accuracy
2. Which of the following is the correct way to import the SHAP library in Python?
easy
A. from shap import explain
B. import SHAP
C. import shap
D. import SHAP as sp

Solution

  1. Step 1: Recall Python import syntax

    Python imports are case-sensitive; the SHAP library is lowercase 'shap'.
  2. Step 2: Check each option

    import shap uses correct lowercase import. import SHAP uses uppercase which is invalid. from shap import explain tries to import a non-existent module 'explain'. import SHAP as sp uses uppercase which is invalid.
  3. Final Answer:

    import shap -> Option C
  4. Quick Check:

    Python imports are case-sensitive [OK]
Hint: Python imports match exact package name in lowercase [OK]
Common Mistakes:
  • Using uppercase letters in import statements
  • Importing non-existent submodules
  • Using uncommon aliases without explanation
3. Given the following Python code using LIME, what will exp.as_list() return?
import lime.lime_tabular
explainer = lime.lime_tabular.LimeTabularExplainer(training_data, feature_names=features)
exp = explainer.explain_instance(test_instance, model.predict_proba)
print(exp.as_list())
medium
A. A list of tuples showing feature names and their importance scores for the test instance
B. The predicted class label for the test instance
C. The training data used to build the explainer
D. A plot object visualizing the model's decision

Solution

  1. Step 1: Understand LIME explanation output

    The explain_instance method returns an explanation object. Calling as_list() gives feature importance as a list of (feature, weight) tuples.
  2. Step 2: Match output to options

    A list of tuples showing feature names and their importance scores for the test instance correctly describes this list. The predicted class label for the test instance is the predicted label, which as_list() does not return. The training data used to build the explainer is training data, unrelated here. A plot object visualizing the model's decision is a plot, which requires a different method.
  3. Final Answer:

    A list of tuples showing feature names and their importance scores for the test instance -> Option A
  4. Quick Check:

    LIME explanation list = feature importance [OK]
Hint: LIME's as_list() shows feature importance tuples [OK]
Common Mistakes:
  • Confusing explanation list with predicted label
  • Expecting training data from explanation
  • Thinking as_list() returns a plot
4. You run SHAP on a model but get an error: AttributeError: 'TreeExplainer' object has no attribute 'shap_values'. What is the likely cause?
medium
A. You used an outdated SHAP version missing the shap_values method
B. The model is not a tree-based model supported by TreeExplainer
C. You forgot to import the SHAP library
D. The input data is missing feature names

Solution

  1. Step 1: Understand TreeExplainer requirements

    TreeExplainer works only with tree-based models like XGBoost or LightGBM. Using it on unsupported models causes attribute errors.
  2. Step 2: Analyze error cause

    The error suggests the method shap_values is missing, likely because the model type is unsupported by TreeExplainer.
  3. Final Answer:

    The model is not a tree-based model supported by TreeExplainer -> Option B
  4. Quick Check:

    TreeExplainer needs tree models [OK]
Hint: TreeExplainer only supports tree models, else error occurs [OK]
Common Mistakes:
  • Assuming missing import causes this error
  • Blaming outdated SHAP version without checking model type
  • Ignoring model compatibility with explainer
5. You want to explain predictions of a complex neural network on tabular data. Which approach best combines SHAP and LIME to get both global and local interpretability?
hard
A. Use SHAP's DeepExplainer for global feature importance and LIME for local explanations on individual samples
B. Use LIME only, as SHAP does not support neural networks
C. Use SHAP's TreeExplainer for local explanations and LIME for global explanations
D. Use neither; neural networks cannot be interpreted

Solution

  1. Step 1: Identify SHAP and LIME strengths

    SHAP's DeepExplainer supports neural networks and provides global feature importance. LIME excels at explaining individual predictions locally.
  2. Step 2: Combine for best interpretability

    Using SHAP for global insights and LIME for local explanations gives a full understanding of model behavior.
  3. Final Answer:

    Use SHAP's DeepExplainer for global feature importance and LIME for local explanations on individual samples -> Option A
  4. Quick Check:

    SHAP global + LIME local = best combo [OK]
Hint: SHAP global + LIME local = full interpretability [OK]
Common Mistakes:
  • Thinking SHAP does not support neural networks
  • Confusing TreeExplainer with DeepExplainer
  • Believing neural networks cannot be interpreted
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard