ML Model Explanation

ML Model Explanation

Guides an AI agent to explain machine learning models with SHAP, LIME, feature importance and partial dependence plots, globally and per prediction.

Skill files3 files

scripts/

templates/

SKILL.md343 lines
1
---
2
name: ML Model Explanation
3
description: Interpret machine learning models using SHAP, LIME, feature importance, partial dependence, and attention visualization for explainability
4
---
5
6
# ML Model Explanation
7
8
Model explainability makes machine learning decisions transparent and interpretable, enabling trust, compliance, debugging, and actionable insights from predictions.
9
10
## Explanation Techniques
11
12
- **Feature Importance**: Global feature contribution to predictions
13
- **SHAP Values**: Game theory-based feature attribution
14
- **LIME**: Local linear approximations for individual predictions
15
- **Partial Dependence Plots**: Feature relationship with predictions
16
- **Attention Maps**: Visualization of model focus areas
17
- **Surrogate Models**: Simpler interpretable approximations
18
19
## Explainability Types
20
21
- **Global**: Overall model behavior and patterns
22
- **Local**: Explanation for individual predictions
23
- **Feature-Level**: Which features matter most
24
- **Model-Level**: How different components interact
25
26
## Python Implementation
27
28
```python
29
import numpy as np
30
import pandas as pd
31
import matplotlib.pyplot as plt
32
import seaborn as sns
33
from sklearn.datasets import make_classification
34
from sklearn.model_selection import train_test_split
35
from sklearn.preprocessing import StandardScaler
36
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
37
from sklearn.linear_model import LogisticRegression
38
from sklearn.tree import DecisionTreeClassifier, plot_tree
39
from sklearn.inspection import partial_dependence, permutation_importance
40
import warnings
41
warnings.filterwarnings('ignore')
42
43
print("=== 1. Feature Importance Analysis ===")
44
45
# Create dataset
46
X, y = make_classification(n_samples=1000, n_features=20, n_informative=10,
47
n_redundant=5, random_state=42)
48
feature_names = [f'Feature_{i}' for i in range(20)]
49
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
50
51
# Train models
52
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
53
rf_model.fit(X_train, y_train)
54
55
gb_model = GradientBoostingClassifier(n_estimators=100, random_state=42)
56
gb_model.fit(X_train, y_train)
57
58
# Feature importance methods
59
print("\n=== Feature Importance Comparison ===")
60
61
# 1. Impurity-based importance (default)
62
impurity_importance = rf_model.feature_importances_
63
64
# 2. Permutation importance
65
perm_importance = permutation_importance(rf_model, X_test, y_test, n_repeats=10, random_state=42)
66
67
# Create comparison dataframe
68
importance_df = pd.DataFrame({
69
'Feature': feature_names,
70
'Impurity': impurity_importance,
71
'Permutation': perm_importance.importances_mean
72
}).sort_values('Impurity', ascending=False)
73
74
print("\nTop 10 Most Important Features (by Impurity):")
75
print(importance_df.head(10)[['Feature', 'Impurity']])
76
77
# 2. SHAP-like Feature Attribution
78
print("\n=== SHAP-like Feature Attribution ===")
79
80
class SimpleShapCalculator:
81
def __init__(self, model, X_background):
82
self.model = model
83
self.X_background = X_background
84
self.baseline = model.predict_proba(X_background.mean(axis=0).reshape(1, -1))[0]
85
86
def predict_difference(self, X_sample):
87
"""Get prediction difference from baseline"""
88
pred = self.model.predict_proba(X_sample)[0]
89
return pred - self.baseline
90
91
def calculate_shap_values(self, X_instance, n_iterations=100):
92
"""Approximate SHAP values"""
93
shap_values = np.zeros(X_instance.shape[1])
94
n_features = X_instance.shape[1]
95
96
for i in range(n_iterations):
97
# Random feature subset
98
subset_mask = np.random.random(n_features) > 0.5
99
100
# With and without feature
101
X_with = X_instance.copy()
102
X_without = X_instance.copy()
103
X_without[0, ~subset_mask] = self.X_background[0, ~subset_mask]
104
105
# Marginal contribution
106
contribution = (self.predict_difference(X_with)[1] -
107
self.predict_difference(X_without)[1])
108
109
shap_values[~subset_mask] += contribution / n_iterations
110
111
return shap_values
112
113
shap_calc = SimpleShapCalculator(rf_model, X_train)
114
115
# Calculate SHAP values for a sample
116
sample_idx = 0
117
shap_vals = shap_calc.calculate_shap_values(X_test[sample_idx:sample_idx+1], n_iterations=50)
118
119
print(f"\nSHAP Values for Sample {sample_idx}:")
120
shap_df = pd.DataFrame({
121
'Feature': feature_names,
122
'SHAP_Value': shap_vals
123
}).sort_values('SHAP_Value', key=abs, ascending=False)
124
125
print(shap_df.head(10)[['Feature', 'SHAP_Value']])
126
127
# 3. Partial Dependence Analysis
128
print("\n=== 3. Partial Dependence Analysis ===")
129
130
# Calculate partial dependence for top features
131
top_features = importance_df['Feature'].head(3).values
132
top_feature_indices = [feature_names.index(f) for f in top_features]
133
134
pd_data = {}
135
for feature_idx in top_feature_indices:
136
pd_result = partial_dependence(rf_model, X_test, [feature_idx])
137
pd_data[feature_names[feature_idx]] = pd_result
138
139
print(f"Partial dependence calculated for features: {list(pd_data.keys())}")
140
141
# 4. LIME - Local Interpretable Model-agnostic Explanations
142
print("\n=== 4. LIME (Local Surrogate Model) ===")
143
144
class SimpleLIME:
145
def __init__(self, model, X_train):
146
self.model = model
147
self.X_train = X_train
148
self.scaler = StandardScaler()
149
self.scaler.fit(X_train)
150
151
def explain_instance(self, instance, n_samples=1000, n_features=10):
152
"""Explain prediction using local linear model"""
153
# Generate perturbed samples
154
scaled_instance = self.scaler.transform(instance.reshape(1, -1))
155
perturbations = np.random.normal(scaled_instance, 0.3, (n_samples, instance.shape[0]))
156
157
# Get predictions
158
predictions = self.model.predict_proba(perturbations)[:, 1]
159
160
# Train local linear model
161
distances = np.sum((perturbations - scaled_instance) ** 2, axis=1)
162
weights = np.exp(-distances)
163
164
# Linear regression weights
165
local_model = LogisticRegression()
166
local_model.fit(perturbations, predictions, sample_weight=weights)
167
168
# Get feature importance
169
feature_weights = np.abs(local_model.coef_[0])
170
top_indices = np.argsort(feature_weights)[-n_features:]
171
172
return {
173
'features': [feature_names[i] for i in top_indices],
174
'weights': feature_weights[top_indices],
175
'prediction': self.model.predict(instance.reshape(1, -1))[0]
176
}
177
178
lime = SimpleLIME(rf_model, X_train)
179
lime_explanation = lime.explain_instance(X_test[0])
180
181
print(f"\nLIME Explanation for Sample 0:")
182
for feat, weight in zip(lime_explanation['features'], lime_explanation['weights']):
183
print(f" {feat}: {weight:.4f}")
184
185
# 5. Decision Tree Visualization
186
print("\n=== 5. Decision Tree Interpretation ===")
187
188
# Train small tree for visualization
189
small_tree = DecisionTreeClassifier(max_depth=3, random_state=42)
190
small_tree.fit(X_train, y_train)
191
192
print(f"Decision Tree (depth=3) trained")
193
print(f"Tree accuracy: {small_tree.score(X_test, y_test):.4f}")
194
195
# 6. Model-agnostic global explanations
196
print("\n=== 6. Global Model Behavior ===")
197
198
class GlobalExplainer:
199
def __init__(self, model):
200
self.model = model
201
202
def get_prediction_distribution(self, X):
203
"""Analyze prediction distribution"""
204
predictions = self.model.predict_proba(X)
205
return {
206
'class_0_mean': predictions[:, 0].mean(),
207
'class_1_mean': predictions[:, 1].mean(),
208
'class_1_std': predictions[:, 1].std()
209
}
210
211
def feature_sensitivity(self, X, feature_idx, n_perturbations=10):
212
"""Measure sensitivity to feature changes"""
213
original_pred = self.model.predict_proba(X)[:, 1].mean()
214
sensitivities = []
215
216
for perturbation_level in np.linspace(0.1, 1.0, n_perturbations):
217
X_perturbed = X.copy()
218
X_perturbed[:, feature_idx] = np.random.normal(
219
X[:, feature_idx].mean(),
220
X[:, feature_idx].std() * perturbation_level,
221
len(X)
222
)
223
perturbed_pred = self.model.predict_proba(X_perturbed)[:, 1].mean()
224
sensitivities.append(abs(perturbed_pred - original_pred))
225
226
return np.array(sensitivities)
227
228
explainer = GlobalExplainer(rf_model)
229
pred_dist = explainer.get_prediction_distribution(X_test)
230
print(f"\nPrediction Distribution:")
231
print(f" Class 0 mean probability: {pred_dist['class_0_mean']:.4f}")
232
print(f" Class 1 mean probability: {pred_dist['class_1_mean']:.4f}")
233
234
# 7. Visualization
235
print("\n=== 7. Explanability Visualizations ===")
236
237
fig, axes = plt.subplots(2, 3, figsize=(16, 10))
238
239
# 1. Feature Importance Comparison
240
top_features_plot = importance_df.head(10)
241
axes[0, 0].barh(top_features_plot['Feature'], top_features_plot['Impurity'], color='steelblue')
242
axes[0, 0].set_xlabel('Importance Score')
243
axes[0, 0].set_title('Feature Importance (Random Forest)')
244
axes[0, 0].invert_yaxis()
245
246
# 2. Permutation vs Impurity Importance
247
axes[0, 1].scatter(importance_df['Impurity'], importance_df['Permutation'], alpha=0.6)
248
axes[0, 1].set_xlabel('Impurity Importance')
249
axes[0, 1].set_ylabel('Permutation Importance')
250
axes[0, 1].set_title('Feature Importance Methods Comparison')
251
axes[0, 1].grid(True, alpha=0.3)
252
253
# 3. SHAP Values
254
shap_sorted = shap_df.head(10).sort_values('SHAP_Value')
255
colors = ['red' if x < 0 else 'green' for x in shap_sorted['SHAP_Value']]
256
axes[0, 2].barh(shap_sorted['Feature'], shap_sorted['SHAP_Value'], color=colors)
257
axes[0, 2].set_xlabel('SHAP Value')
258
axes[0, 2].set_title('SHAP Values for Sample 0')
259
axes[0, 2].axvline(x=0, color='black', linestyle='--', linewidth=0.8)
260
261
# 4. Partial Dependence
262
feature_0_idx = top_feature_indices[0]
263
feature_0_values = np.linspace(X_test[:, feature_0_idx].min(), X_test[:, feature_0_idx].max(), 50)
264
predictions_pd = []
265
for val in feature_0_values:
266
X_temp = X_test.copy()
267
X_temp[:, feature_0_idx] = val
268
pred = rf_model.predict_proba(X_temp)[:, 1].mean()
269
predictions_pd.append(pred)
270
271
axes[1, 0].plot(feature_0_values, predictions_pd, linewidth=2, color='purple')
272
axes[1, 0].set_xlabel(feature_names[feature_0_idx])
273
axes[1, 0].set_ylabel('Average Prediction (Class 1)')
274
axes[1, 0].set_title('Partial Dependence Plot')
275
axes[1, 0].grid(True, alpha=0.3)
276
277
# 5. Model Prediction Distribution
278
pred_proba = rf_model.predict_proba(X_test)[:, 1]
279
axes[1, 1].hist(pred_proba, bins=30, color='coral', edgecolor='black', alpha=0.7)
280
axes[1, 1].set_xlabel('Predicted Probability (Class 1)')
281
axes[1, 1].set_ylabel('Frequency')
282
axes[1, 1].set_title('Prediction Distribution')
283
axes[1, 1].grid(True, alpha=0.3, axis='y')
284
285
# 6. Feature Sensitivity Analysis
286
sensitivities = []
287
for feat_idx in range(min(5, X_test.shape[1])):
288
sensitivity = explainer.feature_sensitivity(X_test, feat_idx, n_perturbations=5)
289
sensitivities.append(sensitivity.mean())
290
291
axes[1, 2].bar(range(min(5, X_test.shape[1])), sensitivities, color='lightgreen', edgecolor='black')
292
axes[1, 2].set_xticks(range(min(5, X_test.shape[1])))
293
axes[1, 2].set_xticklabels([f'F{i}' for i in range(min(5, X_test.shape[1]))])
294
axes[1, 2].set_ylabel('Average Sensitivity')
295
axes[1, 2].set_title('Feature Sensitivity to Perturbations')
296
axes[1, 2].grid(True, alpha=0.3, axis='y')
297
298
plt.tight_layout()
299
plt.savefig('model_explainability.png', dpi=100, bbox_inches='tight')
300
print("\nVisualization saved as 'model_explainability.png'")
301
302
# 8. Summary
303
print("\n=== Explainability Summary ===")
304
print(f"Total Features Analyzed: {len(feature_names)}")
305
print(f"Most Important Feature: {importance_df.iloc[0]['Feature']}")
306
print(f"Importance Score: {importance_df.iloc[0]['Impurity']:.4f}")
307
print(f"Model Accuracy: {rf_model.score(X_test, y_test):.4f}")
308
print(f"Average Prediction Confidence: {pred_proba.mean():.4f}")
309
310
print("\nML model explanation setup completed!")
311
```
312
313
## Explanation Techniques Comparison
314
315
- **Feature Importance**: Fast, global, model-specific
316
- **SHAP**: Theoretically sound, game-theory based, computationally expensive
317
- **LIME**: Model-agnostic, local explanations, interpretable
318
- **PDP**: Shows feature relationships, can be misleading with correlations
319
- **Attention**: Works for neural networks, interpretable attention weights
320
321
## Interpretability vs Accuracy Trade-off
322
323
- Linear models: Highly interpretable, lower accuracy
324
- Tree models: Interpretable, moderate accuracy
325
- Neural networks: High accuracy, less interpretable
326
- Ensemble models: High accuracy, need explanation techniques
327
328
## Regulatory Compliance
329
330
- GDPR: Right to explanation for automated decisions
331
- Fair Lending: Explainability for credit decisions
332
- Insurance: Transparency in underwriting
333
- Healthcare: Medical decision explanation
334
335
## Deliverables
336
337
- Feature importance rankings
338
- Local explanations for predictions
339
- Partial dependence plots
340
- Global behavior analysis
341
- Model interpretation report
342
- Explanation dashboard
343

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…