Skip to main content

trustformers_debug/interpretability/
shap.rs

1//! SHAP (SHapley Additive exPlanations) analysis
2//!
3//! This module implements SHAP analysis for model interpretability, providing
4//! feature importance and contribution analysis.
5
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10/// SHAP (SHapley Additive exPlanations) analysis result
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct ShapAnalysisResult {
13    /// Analysis timestamp
14    pub timestamp: DateTime<Utc>,
15    /// SHAP values for each feature
16    pub shap_values: HashMap<String, f64>,
17    /// Feature names
18    pub feature_names: Vec<String>,
19    /// Base value (expected model output)
20    pub base_value: f64,
21    /// Model prediction
22    pub prediction: f64,
23    /// Feature contributions (sorted by importance)
24    pub feature_contributions: Vec<FeatureContribution>,
25    /// Top positive features
26    pub top_positive_features: Vec<FeatureContribution>,
27    /// Top negative features
28    pub top_negative_features: Vec<FeatureContribution>,
29    /// SHAP interaction values (if computed)
30    pub interaction_values: Option<HashMap<(String, String), f64>>,
31    /// Summary statistics
32    pub summary: ShapSummary,
33}
34
35/// Individual feature contribution
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct FeatureContribution {
38    /// Feature name
39    pub feature_name: String,
40    /// SHAP value (contribution to prediction)
41    pub shap_value: f64,
42    /// Feature value
43    pub feature_value: f64,
44    /// Absolute importance rank
45    pub importance_rank: usize,
46    /// Contribution percentage
47    pub contribution_percentage: f64,
48}
49
50/// SHAP analysis summary
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct ShapSummary {
53    /// Total positive contribution
54    pub total_positive_contribution: f64,
55    /// Total negative contribution
56    pub total_negative_contribution: f64,
57    /// Number of important features (above threshold)
58    pub num_important_features: usize,
59    /// Feature importance distribution
60    pub importance_distribution: HashMap<String, f64>,
61    /// Model explanation completeness (0.0 to 1.0)
62    pub explanation_completeness: f64,
63}