Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the shap 0.54, LIME 0.2.0.1, transformers 5.23, PyTorch 2.15, SciPy 1.18 and scikit-learn 1.9 documentation.
AI Model Explainability for Security: Understanding Black Box Decisions
As AI systems increasingly make critical decisions in security contexts - from threat detection to access control - the ability to explain these decisions becomes essential for trust, compliance, and debugging. This guide covers practical techniques for making AI models interpretable and auditable.
Why Explainability Matters for Security
In security applications, explainability serves multiple critical purposes:
- Compliance: GDPR Article 22 restricts decisions based solely on automated processing that produce legal or similarly significant effects and requires safeguards such as human intervention and the right to contest the decision; Articles 13-15 require meaningful information about the logic involved. Explanations help you meet those duties; the law does not require an explanation for every model output.
- Debugging: Understanding why a model flagged (or missed) a threat
- Trust: Security teams need confidence in AI recommendations
- Adversarial Defense: Identifying if models are being manipulated
- Audit Trail: Documenting decision rationale for investigations
SHAP (SHapley Additive exPlanations)
Implementing SHAP for Security Models
# shap_security_explanations.py
"""
SHAP-based explanations for security ML models.
"""
from dataclasses import dataclass
from typing import Any, List, Optional
import numpy as np
import pandas as pd
import shap
@dataclass
class FeatureExplanation:
"""Explanation for a single feature's contribution."""
feature_name: str
feature_value: Any
shap_value: float
contribution_direction: str # 'supports_prediction' or 'opposes_prediction'
relative_importance: float
@dataclass
class PredictionExplanation:
"""Complete explanation for a prediction."""
prediction: str
confidence: float
base_value: float
feature_explanations: List[FeatureExplanation]
top_contributors: List[str]
summary: str
class SecurityModelExplainer:
"""
Human-readable explanations for a scikit-learn style classifier
(the model must expose predict_proba).
"""
def __init__(self, model, feature_names: List[str], class_names: List[str]):
if not hasattr(model, "predict_proba"):
raise TypeError("SecurityModelExplainer needs a classifier with predict_proba")
self.model = model
self.feature_names = feature_names
self.class_names = class_names
self.explainer = None
self.background_data = None
def initialize_explainer(
self,
background_data: np.ndarray,
explainer_type: str = "tree"
):
"""
Initialize SHAP explainer with background data.
Args:
background_data: Representative sample for computing expectations
explainer_type: 'tree', 'kernel', or 'linear'
"""
self.background_data = background_data
if explainer_type == "tree":
self.explainer = shap.TreeExplainer(self.model)
elif explainer_type == "kernel":
self.explainer = shap.KernelExplainer(
self.model.predict_proba,
shap.sample(background_data, 100)
)
elif explainer_type == "linear":
self.explainer = shap.LinearExplainer(self.model, background_data)
else:
raise ValueError(f"Unknown explainer type: {explainer_type}")
def _class_shap_values(self, instance_2d: np.ndarray, predicted_class: int) -> np.ndarray:
"""SHAP values of one instance for the predicted class."""
shap_values = self.explainer.shap_values(instance_2d)
if isinstance(shap_values, list):
# shap releases before 0.45 returned one array per class
return np.asarray(shap_values[predicted_class])[0]
shap_values = np.asarray(shap_values)
if shap_values.ndim == 3:
# shap >= 0.45: (n_samples, n_features, n_outputs)
return shap_values[0, :, predicted_class]
# Single-output model (for example a binary linear model in log-odds):
# values refer to class 1, so flip the sign when explaining class 0
values = shap_values[0]
return -values if predicted_class == 0 else values
def _base_value(self, predicted_class: int) -> float:
expected = np.atleast_1d(np.asarray(self.explainer.expected_value, dtype=float))
if expected.size > 1:
return float(expected[predicted_class])
return float(-expected[0] if predicted_class == 0 else expected[0])
def explain_prediction(
self,
instance: np.ndarray,
top_k: int = 5
) -> PredictionExplanation:
"""
Generate detailed explanation for a single prediction.
Args:
instance: Single instance to explain (1D array)
top_k: Number of top contributing features to highlight
"""
if self.explainer is None:
raise RuntimeError("Explainer not initialized. Call initialize_explainer first.")
instance_2d = instance.reshape(1, -1)
proba = self.model.predict_proba(instance_2d)[0]
predicted_class = int(np.argmax(proba))
confidence = float(proba[predicted_class])
shap_vals = self._class_shap_values(instance_2d, predicted_class)
base_value = self._base_value(predicted_class)
feature_explanations = []
abs_shap = np.abs(shap_vals)
max_abs = np.max(abs_shap) if np.max(abs_shap) > 0 else 1
for i, (name, value, shap_val) in enumerate(
zip(self.feature_names, instance, shap_vals)
):
feature_explanations.append(FeatureExplanation(
feature_name=name,
feature_value=value,
shap_value=float(shap_val),
contribution_direction='supports_prediction' if shap_val > 0 else 'opposes_prediction',
relative_importance=float(abs_shap[i] / max_abs)
))
feature_explanations.sort(key=lambda x: abs(x.shap_value), reverse=True)
top_contributors = [f.feature_name for f in feature_explanations[:top_k]]
summary = self._generate_summary(
predicted_class,
confidence,
feature_explanations[:top_k]
)
return PredictionExplanation(
prediction=self.class_names[predicted_class],
confidence=confidence,
base_value=base_value,
feature_explanations=feature_explanations,
top_contributors=top_contributors,
summary=summary
)
def _generate_summary(
self,
predicted_class: int,
confidence: float,
top_features: List[FeatureExplanation]
) -> str:
"""Generate human-readable summary of the prediction."""
class_name = self.class_names[predicted_class]
summary = f"This instance was classified as {class_name} ({confidence:.1%} model probability). "
if top_features:
supporting = [f for f in top_features if f.contribution_direction == 'supports_prediction']
opposing = [f for f in top_features if f.contribution_direction == 'opposes_prediction']
if supporting:
factors = [f"'{f.feature_name}' = {f.feature_value}" for f in supporting[:3]]
summary += f"Factors supporting this classification: {', '.join(factors)}. "
if opposing:
factors = [f"'{f.feature_name}' = {f.feature_value}" for f in opposing[:2]]
summary += f"Factors against it: {', '.join(factors)}."
return summary
def explain_batch(
self,
instances: np.ndarray,
output_format: str = "dataframe"
) -> Any:
"""
Explain multiple predictions.
Args:
instances: Multiple instances to explain
output_format: 'dataframe', 'json', or 'explanations'
"""
explanations = [self.explain_prediction(instance) for instance in instances]
if output_format == "explanations":
return explanations
elif output_format == "dataframe":
rows = []
for i, exp in enumerate(explanations):
row = {
'instance_id': i,
'prediction': exp.prediction,
'confidence': exp.confidence,
'summary': exp.summary
}
for j, contributor in enumerate(exp.top_contributors):
row[f'top_factor_{j+1}'] = contributor
rows.append(row)
return pd.DataFrame(rows)
elif output_format == "json":
return [self._explanation_to_dict(exp) for exp in explanations]
raise ValueError(f"Unknown output format: {output_format}")
@staticmethod
def _plain(value: Any) -> Any:
return value.item() if isinstance(value, np.generic) else value
def _explanation_to_dict(self, exp: PredictionExplanation) -> dict:
"""Convert explanation to dictionary for JSON serialization."""
return {
'prediction': exp.prediction,
'confidence': exp.confidence,
'base_value': exp.base_value,
'summary': exp.summary,
'top_contributors': exp.top_contributors,
'feature_explanations': [
{
'feature': f.feature_name,
'value': self._plain(f.feature_value),
'shap_value': f.shap_value,
'direction': f.contribution_direction,
'importance': f.relative_importance
}
for f in exp.feature_explanations
]
}
def generate_audit_report(
self,
instance: np.ndarray,
instance_id: str,
analyst_notes: Optional[str] = None
) -> dict:
"""
Generate a decision record that a human reviewer can check.
"""
explanation = self.explain_prediction(instance)
return {
'report_type': 'AI_DECISION_EXPLANATION',
'instance_id': instance_id,
'generated_at': pd.Timestamp.now(tz='UTC').isoformat(),
'model_info': {
'model_type': type(self.model).__name__,
'num_features': len(self.feature_names),
'num_classes': len(self.class_names)
},
'decision': {
'classification': explanation.prediction,
'model_probability': explanation.confidence,
'shap_base_value': explanation.base_value
},
'explanation': {
'method': 'SHAP',
'summary': explanation.summary,
'top_contributing_factors': [
{
'rank': i + 1,
'feature': f.feature_name,
'observed_value': self._plain(f.feature_value),
'contribution': f.shap_value,
'direction': f.contribution_direction
}
for i, f in enumerate(explanation.feature_explanations[:10])
]
},
'analyst_notes': analyst_notes,
'note': (
"Generated to support human review of an automated decision. "
"It is not, by itself, a determination of GDPR compliance."
)
}
class ThreatDetectionExplainer(SecurityModelExplainer):
"""
Specialized explainer for threat detection models.
"""
def __init__(self, model, feature_names: List[str]):
super().__init__(
model,
feature_names,
class_names=['Benign', 'Malicious']
)
# Feature categories for better explanations
self.feature_categories = {
'network': ['src_port', 'dst_port', 'protocol', 'packet_size', 'flow_duration'],
'behavioral': ['request_rate', 'unique_destinations', 'failed_attempts'],
'content': ['payload_entropy', 'suspicious_patterns', 'encoding_type'],
'temporal': ['hour_of_day', 'day_of_week', 'time_since_last']
}
def explain_threat(
self,
instance: np.ndarray,
include_recommendations: bool = True
) -> dict:
"""
Generate threat-specific explanation with recommendations.
"""
explanation = self.explain_prediction(instance)
result = {
'threat_assessment': {
'is_threat': explanation.prediction == 'Malicious',
'model_probability': explanation.confidence,
'severity': self._calculate_severity(explanation)
},
'explanation': explanation.summary,
'contributing_factors': []
}
for feat_exp in explanation.feature_explanations[:10]:
category = self._get_feature_category(feat_exp.feature_name)
result['contributing_factors'].append({
'factor': feat_exp.feature_name,
'category': category,
'value': self._plain(feat_exp.feature_value),
'impact': 'High' if feat_exp.relative_importance > 0.7 else
'Medium' if feat_exp.relative_importance > 0.3 else 'Low',
'direction': feat_exp.contribution_direction
})
if include_recommendations and explanation.prediction == 'Malicious':
result['recommendations'] = self._generate_recommendations(
explanation.feature_explanations[:5]
)
return result
def _calculate_severity(self, explanation: PredictionExplanation) -> str:
"""Map model probability to a triage severity (tune to your alert budget)."""
if explanation.prediction == 'Benign':
return 'None'
if explanation.confidence > 0.9:
return 'Critical'
elif explanation.confidence > 0.7:
return 'High'
elif explanation.confidence > 0.5:
return 'Medium'
else:
return 'Low'
def _get_feature_category(self, feature_name: str) -> str:
"""Get category for a feature."""
for category, features in self.feature_categories.items():
if any(f in feature_name.lower() for f in features):
return category
return 'other'
def _generate_recommendations(
self,
top_factors: List[FeatureExplanation]
) -> List[str]:
"""Generate review steps for the factors that pushed towards 'Malicious'."""
recommendations = []
for factor in top_factors:
if factor.contribution_direction != 'supports_prediction':
continue
name = factor.feature_name.lower()
if 'port' in name:
recommendations.append(
f"Review firewall rules for port {factor.feature_value}"
)
elif 'rate' in name or 'frequency' in name:
recommendations.append("Consider implementing rate limiting")
elif 'entropy' in name:
recommendations.append(
"Inspect payload for potential obfuscation or encryption"
)
elif 'failed' in name:
recommendations.append(
"Review authentication logs for brute force attempts"
)
elif 'destination' in name:
recommendations.append(
"Investigate communication with unusual destinations"
)
return recommendations[:5]LIME (Local Interpretable Model-agnostic Explanations)
# lime_security_explanations.py
"""
LIME-based explanations for security models.
"""
import html
import re
from typing import Callable, List, Optional
import numpy as np
from lime.lime_tabular import LimeTabularExplainer
from lime.lime_text import LimeTextExplainer
class SecurityTextExplainer:
"""
LIME explanations for text-based security models
(e.g., phishing detection, malware classification).
Weights are always computed for `risk_class` (the phishing/malicious
class), so a positive weight means "pushes towards the risky class".
"""
def __init__(
self,
classifier_fn: Callable,
class_names: List[str],
risk_class: int = 1
):
"""
Args:
classifier_fn: Function that takes list of texts and returns probabilities
class_names: Names of classification classes
risk_class: Index of the class that means "risky"
"""
self.classifier_fn = classifier_fn
self.class_names = class_names
self.risk_class = risk_class
self.explainer = LimeTextExplainer(
class_names=class_names,
split_expression=r'\W+',
bow=True
)
def explain_text(
self,
text: str,
num_features: int = 10,
num_samples: int = 5000
) -> dict:
"""
Explain a text classification prediction.
Args:
text: Text to explain
num_features: Number of features in explanation
num_samples: Number of perturbed samples to generate
"""
proba = self.classifier_fn([text])[0]
predicted_class = int(np.argmax(proba))
# explain_instance explains labels=(1,) by default; name the label explicitly
explanation = self.explainer.explain_instance(
text,
self.classifier_fn,
labels=(self.risk_class,),
num_features=num_features,
num_samples=num_samples
)
feature_weights = explanation.as_list(label=self.risk_class)
return {
'text': text,
'prediction': self.class_names[predicted_class],
'confidence': float(proba[predicted_class]),
'explanation': {
'explained_class': self.class_names[self.risk_class],
'important_words': [
{
'word': word,
'weight': float(weight),
'direction': 'suspicious' if weight > 0 else 'benign'
}
for word, weight in feature_weights
],
'highlighted_html': self._highlight_text(text, feature_weights)
},
'summary': self._generate_text_summary(
self.class_names[predicted_class],
feature_weights
)
}
def _highlight_text(
self,
text: str,
feature_weights: List[tuple]
) -> str:
"""
Return HTML with important words highlighted.
The analysed text is untrusted (it may be a phishing email), so every
piece of it is HTML-escaped, and all words are matched in a single pass
so the inserted markup is never re-matched.
"""
weights = {word.lower(): weight for word, weight in feature_weights}
if not weights:
return html.escape(text)
alternatives = sorted(weights, key=len, reverse=True)
pattern = re.compile(
r"\b(" + "|".join(re.escape(w) for w in alternatives) + r")\b",
re.IGNORECASE
)
parts = []
last = 0
for match in pattern.finditer(text):
parts.append(html.escape(text[last:match.start()]))
color = 'red' if weights[match.group(0).lower()] > 0 else 'green'
parts.append(
f'<span style="background-color: {color}; padding: 2px;">'
f'{html.escape(match.group(0))}</span>'
)
last = match.end()
parts.append(html.escape(text[last:]))
return "".join(parts)
def _generate_text_summary(
self,
prediction: str,
feature_weights: List[tuple]
) -> str:
"""Generate natural language summary."""
suspicious_words = [w for w, weight in feature_weights if weight > 0][:3]
benign_words = [w for w, weight in feature_weights if weight < 0][:3]
summary = f"The text was classified as '{prediction}'. "
if suspicious_words:
summary += f"Suspicious indicators: {', '.join(suspicious_words)}. "
if benign_words:
summary += f"Benign indicators: {', '.join(benign_words)}."
return summary
class SecurityTabularExplainer:
"""
LIME-based explanations for tabular security data.
"""
def __init__(
self,
training_data: np.ndarray,
feature_names: List[str],
class_names: List[str],
categorical_features: Optional[List[int]] = None,
risk_class: int = 1
):
self.feature_names = feature_names
self.class_names = class_names
self.risk_class = risk_class
self.explainer = LimeTabularExplainer(
training_data,
feature_names=feature_names,
class_names=class_names,
categorical_features=categorical_features or [],
mode='classification'
)
def explain_instance(
self,
instance: np.ndarray,
predict_fn: Callable,
num_features: int = 10
) -> dict:
"""
Explain a single prediction (weights computed for risk_class).
"""
explanation = self.explainer.explain_instance(
instance,
predict_fn,
labels=(self.risk_class,),
num_features=num_features
)
proba = predict_fn(instance.reshape(1, -1))[0]
predicted_class = int(np.argmax(proba))
feature_weights = explanation.as_list(label=self.risk_class)
return {
'prediction': self.class_names[predicted_class],
'confidence': float(proba[predicted_class]),
'explained_class': self.class_names[self.risk_class],
'local_model_prediction': float(
np.ravel(explanation.local_pred[self.risk_class])[0]
),
'feature_contributions': [
{
'condition': condition,
'weight': float(weight),
'direction': 'increases_risk' if weight > 0 else 'decreases_risk'
}
for condition, weight in feature_weights
],
'intercept': float(explanation.intercept[self.risk_class])
}Attention Visualization for Transformers
# attention_visualization.py
"""
Attention visualization for transformer-based security models.
Attention weights show where the model attends; treat them as a diagnostic
signal, not as a complete explanation of the decision.
"""
import torch
import numpy as np
from typing import List, Dict, Tuple, Optional
from transformers import AutoTokenizer, AutoModel
import matplotlib.pyplot as plt
import seaborn as sns
class AttentionExplainer:
"""
Visualize and explain attention patterns in transformer models.
"""
def __init__(
self,
model_name: str,
device: str = 'cpu'
):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
# "eager" materializes the attention matrix, so it can be returned
self.model = AutoModel.from_pretrained(
model_name,
attn_implementation="eager",
output_attentions=True
).to(device)
self.model.eval()
self.device = device
def get_attention_weights(
self,
text: str
) -> Tuple[List[str], np.ndarray]:
"""
Extract attention weights for input text.
Returns:
tokens: List of tokens
attention: Attention weights [num_layers, num_heads, seq_len, seq_len]
"""
inputs = self.tokenizer(
text,
return_tensors='pt',
truncation=True,
max_length=512
).to(self.device)
with torch.no_grad():
outputs = self.model(**inputs)
if outputs.attentions is None:
raise RuntimeError("Model did not return attentions; check attn_implementation")
# Stack all layers: [layers, batch, heads, seq, seq]
attention_tensor = torch.stack(outputs.attentions)
attention_np = attention_tensor.squeeze(1).cpu().numpy()
tokens = self.tokenizer.convert_ids_to_tokens(inputs['input_ids'][0])
return tokens, attention_np
def explain_with_attention(
self,
text: str,
layer: int = -1,
head: Optional[int] = None
) -> dict:
"""
Generate explanation based on attention patterns.
Args:
text: Input text
layer: Which layer to analyze (-1 for last)
head: Which attention head (None for average)
"""
tokens, attention = self.get_attention_weights(text)
layer_attention = attention[layer] # [heads, seq, seq]
if head is None:
token_attention = layer_attention.mean(axis=0)
else:
token_attention = layer_attention[head]
# Attention from the first token (CLS in BERT-style models), skipping
# the first and last special tokens
cls_attention = token_attention[0, 1:-1]
relevant_tokens = tokens[1:-1]
if cls_attention.sum() > 0:
cls_attention = cls_attention / cls_attention.sum()
top_indices = np.argsort(cls_attention)[::-1][:10]
return {
'tokens': relevant_tokens,
'attention_weights': cls_attention.tolist(),
'top_attended_tokens': [
{
'token': relevant_tokens[i],
'attention': float(cls_attention[i]),
'position': int(i)
}
for i in top_indices
],
'attention_matrix': token_attention.tolist()
}
def visualize_attention(
self,
text: str,
layer: int = -1,
head: Optional[int] = None,
save_path: Optional[str] = None
):
"""
Create attention heatmap visualization.
"""
tokens, attention = self.get_attention_weights(text)
if head is None:
attn_matrix = attention[layer].mean(axis=0)
title = f"Averaged Attention (Layer {layer})"
else:
attn_matrix = attention[layer, head]
title = f"Attention Head {head} (Layer {layer})"
max_tokens = 30
if len(tokens) > max_tokens:
tokens = tokens[:max_tokens]
attn_matrix = attn_matrix[:max_tokens, :max_tokens]
fig, ax = plt.subplots(figsize=(12, 10))
sns.heatmap(
attn_matrix,
xticklabels=tokens,
yticklabels=tokens,
cmap='YlOrRd',
ax=ax
)
ax.set_title(title)
ax.set_xlabel('Key Tokens')
ax.set_ylabel('Query Tokens')
plt.xticks(rotation=45, ha='right')
plt.yticks(rotation=0)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.close()
else:
plt.show()
def get_token_importance(
self,
text: str,
method: str = 'attention_rollout'
) -> Dict[str, float]:
"""
Calculate token importance using attention-based methods.
Args:
method: 'attention_rollout', 'layer_average', or 'last_layer'
"""
tokens, attention = self.get_attention_weights(text)
if method == 'last_layer':
# Last-layer attention from the first token, averaged over heads
importance = attention[-1].mean(axis=0)[0]
elif method == 'attention_rollout':
# Attention rollout: multiply head-averaged attention across layers
rollout = np.eye(attention.shape[-1])
for layer_attn in attention:
layer_avg = layer_attn.mean(axis=0)
# Account for the residual connection
layer_avg = 0.5 * layer_avg + 0.5 * np.eye(layer_avg.shape[0])
layer_avg = layer_avg / layer_avg.sum(axis=-1, keepdims=True)
rollout = rollout @ layer_avg
importance = rollout[0]
elif method == 'layer_average':
# First-token attention averaged over heads and layers
importance = np.zeros(attention.shape[-1])
for layer_attn in attention:
importance += layer_attn.mean(axis=0)[0]
importance = importance / len(attention)
else:
raise ValueError(f"Unknown method: {method}")
# Keyed by position, because the same token can appear more than once
return {
f"{i}:{token}": float(imp)
for i, (token, imp) in enumerate(zip(tokens, importance))
}Counterfactual Explanations
# counterfactual_explanations.py
"""
Counterfactual explanations for security decisions.
"""
import numpy as np
from typing import List, Dict, Optional, Callable, Tuple
from dataclasses import dataclass
from scipy.optimize import minimize
@dataclass
class Counterfactual:
"""A counterfactual explanation."""
original_instance: np.ndarray
counterfactual_instance: np.ndarray
original_prediction: str
counterfactual_prediction: str
changes: List[Dict]
distance: float
class CounterfactualExplainer:
"""
Search for small changes to the mutable features that flip a prediction.
Numeric features only: mark categorical features as immutable, or use a
dedicated counterfactual library for them.
"""
def __init__(
self,
predict_proba_fn: Callable[[np.ndarray], np.ndarray],
feature_names: List[str],
feature_ranges: Dict[str, Tuple[float, float]],
immutable_features: Optional[List[str]] = None
):
"""
Args:
predict_proba_fn: Function returning class probabilities, shape (n, n_classes)
feature_names: Names of features
feature_ranges: Valid (min, max) range for each mutable feature
immutable_features: Features that must not change
"""
self.predict_proba_fn = predict_proba_fn
self.feature_names = feature_names
self.feature_ranges = feature_ranges
self.immutable_features = set(immutable_features or [])
self.mutable_idx = [
i for i, name in enumerate(feature_names)
if name not in self.immutable_features
]
def _predict_class(self, x: np.ndarray) -> int:
return int(np.argmax(self.predict_proba_fn(x.reshape(1, -1))[0]))
def generate_counterfactual(
self,
instance: np.ndarray,
target_class: int,
max_changes: int = 5,
distance_weight: float = 0.1,
n_restarts: int = 10,
seed: Optional[int] = None
) -> Optional[Counterfactual]:
"""
Find small changes that achieve the target prediction.
Returns None if the instance already has the target class or no
counterfactual is found within the bounds.
"""
rng = np.random.default_rng(seed)
instance = instance.astype(float)
original_class = self._predict_class(instance)
if original_class == target_class or not self.mutable_idx:
return None
bounds = [
self.feature_ranges.get(self.feature_names[i], (None, None))
for i in self.mutable_idx
]
def assemble(z: np.ndarray) -> np.ndarray:
# Immutable features keep their original values
x = instance.copy()
x[self.mutable_idx] = z
return x
def objective(z: np.ndarray) -> float:
x = assemble(z)
proba = self.predict_proba_fn(x.reshape(1, -1))[0][target_class]
num_changes = int(np.sum(np.abs(x - instance) > 1e-6))
change_penalty = max(0, num_changes - max_changes) * 10
return -proba + distance_weight * self._calculate_distance(instance, x) + change_penalty
best_cf = None
best_score = float('inf')
for _ in range(n_restarts):
z0 = instance[self.mutable_idx] + rng.normal(0, 0.1, len(self.mutable_idx))
lows = [b[0] if b[0] is not None else -np.inf for b in bounds]
highs = [b[1] if b[1] is not None else np.inf for b in bounds]
z0 = np.clip(z0, lows, highs)
# Powell is derivative-free, which suits piecewise-constant models
# such as tree ensembles, and respects bounds
result = minimize(objective, z0, method='Powell', bounds=bounds)
candidate = assemble(result.x)
if self._predict_class(candidate) == target_class and result.fun < best_score:
best_cf = candidate
best_score = result.fun
if best_cf is None:
return None
return Counterfactual(
original_instance=instance.copy(),
counterfactual_instance=best_cf,
original_prediction=str(original_class),
counterfactual_prediction=str(target_class),
changes=self._identify_changes(instance, best_cf),
distance=self._calculate_distance(instance, best_cf)
)
def _calculate_distance(
self,
x1: np.ndarray,
x2: np.ndarray
) -> float:
"""Calculate range-normalized L1 distance between instances."""
distance = 0.0
for i in self.mutable_idx:
min_val, max_val = self.feature_ranges.get(self.feature_names[i], (0, 1))
range_size = max_val - min_val
if range_size > 0:
distance += abs(x1[i] - x2[i]) / range_size
else:
distance += abs(x1[i] - x2[i])
return distance / len(self.feature_names)
def _identify_changes(
self,
original: np.ndarray,
counterfactual: np.ndarray,
threshold: float = 1e-6
) -> List[Dict]:
"""Identify which features changed."""
changes = []
for i, name in enumerate(self.feature_names):
diff = abs(original[i] - counterfactual[i])
if diff > threshold:
changes.append({
'feature': name,
'original_value': float(original[i]),
'counterfactual_value': float(counterfactual[i]),
'change': float(counterfactual[i] - original[i]),
'change_percentage': float(diff / abs(original[i])) * 100 if original[i] != 0 else float('inf')
})
changes.sort(key=lambda x: abs(x['change']), reverse=True)
return changes
def generate_explanation(
self,
instance: np.ndarray,
target_class: int = 0
) -> str:
"""Generate natural language counterfactual explanation."""
cf = self.generate_counterfactual(instance, target_class)
if cf is None:
return ("No counterfactual found: the instance already has the target class, "
"or no change within the feature ranges flips the prediction.")
explanation = f"To change the prediction from '{cf.original_prediction}' to '{cf.counterfactual_prediction}', "
if len(cf.changes) == 1:
change = cf.changes[0]
explanation += f"change '{change['feature']}' from {change['original_value']:.2f} to {change['counterfactual_value']:.2f}."
else:
explanation += "make the following changes: "
change_strs = [
f"'{change['feature']}' from {change['original_value']:.2f} to {change['counterfactual_value']:.2f}"
for change in cf.changes[:5]
]
explanation += "; ".join(change_strs) + "."
return explanationConclusion
AI explainability is essential for security applications where understanding model decisions can mean the difference between catching a threat and missing an attack. Key techniques covered include:
- SHAP for feature-level importance with game-theoretic foundations
- LIME for local, model-agnostic explanations
- Attention visualization for transformer-based models
- Counterfactual explanations showing what changes would alter predictions
These techniques enable security teams to trust, debug, and comply with regulations when deploying AI systems in critical security contexts.
Official references
- Release v0.45.0, shap/shap on GitHub
- lime/lime_text.py, marcotcr/lime on GitHub
- Attention backends, Hugging Face Transformers documentation
- scipy.optimize.minimize, SciPy Manual
Related on this site: AI Model Security Checklist: Dev to Production, AI Model Versioning: Secure MLOps Model Management, Every AI Security Startup Got Acquired. Now What?. More articles in the AI Security category, and the engineering work behind them is on the services page.
Need an AI system built and running in production, with the scope agreed in writing and a delivery guarantee? See how a DeviDevs Sprint works →