To compute and visualize SHAP values and save accessible SVG/PNG assets, follow these steps: prepare model/data, compute SHAP explainer and values, create clear visuals with simplified annotations and high-contrast palettes, embed alt text and captions, export SVG/PNG, and save accompanying machine-readable metadata (JSON) and plain-text captions for screen readers.python
# python pseudocode
import shap
import matplotlib.pyplot as plt
import json
from pathlib import Path
# 1. Prepare
model = trained_sklearn_model
X = feature_dataframe # Pandas DataFrame
background = X.sample(100) # for KernelExplainer; smaller for speed
# 2. Compute SHAP values
if model_is_tree_based:
explainer = shap.TreeExplainer(model, data=background)
else:
explainer = shap.KernelExplainer(model.predict_proba, background)
shap_values = explainer.shap_values(X) # list for multiclass
# 3. Visualize (example: summary plot and single prediction force plot)
out_dir = Path("outputs/shap_viz"); out_dir.mkdir(parents=True, exist_ok=True)
# Summary plot - simplified, high-contrast
plt.figure(figsize=(8,6))
shap.summary_plot(shap_values, X, show=False, plot_type="dot", color_bar=False)
plt.title("SHAP summary: feature impact on model output", fontsize=14)
plt.tight_layout()
svg_path = out_dir / "shap_summary.svg"
png_path = out_dir / "shap_summary.png"
plt.savefig(svg_path, format="svg") # vector: scalable, editable
plt.savefig(png_path, dpi=300) # raster: fallback
plt.close()
# Single prediction explanation (force or bar)
i = 0 # index to explain
plt.figure(figsize=(6,4))
shap.plots.bar(shap_values[i], feature_names=X.columns, show=False)
plt.title(f"Top feature contributions for sample {i}", fontsize=12)
plt.tight_layout()
plt.savefig(out_dir / f"shap_bar_{i}.svg", format="svg")
plt.savefig(out_dir / f"shap_bar_{i}.png", dpi=300)
plt.close()
# 4. Accessibility artifacts
metadata = {
"files": [
{
"filename": svg_path.name,
"alt_text": "Bar chart showing top features contributing to prediction: feature A positive, feature B negative. Colors high contrast. See caption for details.",
"caption": "This summary shows the magnitude and direction of each feature's effect on predictions. Positive values increase predicted probability; negative decrease.",
"labels": list(X.columns)
}
],
"model": {"type": model.__class__.__name__, "explainer": explainer.__class__.__name__}
}
with open(out_dir / "shap_viz_metadata.json", "w") as f:
json.dump(metadata, f, indent=2)
# 5. Save plain-text caption for screen readers
with open(out_dir / "shap_summary_caption.txt", "w") as f:
f.write(metadata["files"][0]["caption"])
Key considerations:- Use SVG for scalability and easier text extraction; provide PNG fallback.- Keep plots uncluttered: show top-N features, larger fonts (>=12pt), high-contrast palettes, avoid relying on color alone (use shapes/patterns or +/- labels).- Provide descriptive alt text and a separate plain-text caption that includes a short interpretation and numeric highlights (e.g., "feature X contributed +0.42 to the log-odds").- Export a machine-readable JSON with filename → alt_text → caption → labels to include in portfolio HTML pages (use aria-describedby linking to caption).- For large datasets or non-tree models, sample background or use SHAP approximation to reduce compute time.- Validate visuals with a11y tools (color contrast checkers, screen-reader tests).