Examples
Real-world examples and code snippets to help you integrate explainable AI into your projects.
Credit Risk Prediction
Explain credit approval decisions with SHAP to provide transparency for loan applicants.
python
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from blackbox_core import Explainer
# Load credit data
df = pd.read_csv('credit_data.csv')
X = df.drop('approved', axis=1)
y = df['approved']
# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X, y)
# Create explainer
explainer = Explainer(model, method='shap')
# Explain a declined application
declined_application = X[y == 0].iloc[0:1]
explanation = explainer.explain(
data=declined_application,
feature_names=X.columns.tolist()
)
# Show why it was declined
explanation.plot()
# Get top reasons
reasons = explanation.get_top_features(n=5)
print("Top reasons for decline:", reasons)Medical Diagnosis Assistant
Use LIME to explain disease predictions and help doctors understand AI-assisted diagnoses.
python
import numpy as np
from tensorflow import keras
from blackbox_core import Explainer
# Load trained diagnostic model
model = keras.models.load_model('diagnosis_model.h5')
# Patient data
patient_data = np.array([[...]]) # Patient symptoms and vitals
feature_names = ['age', 'blood_pressure', 'glucose', ...]
# Create LIME explainer
explainer = Explainer(model, method='lime')
# Explain diagnosis
explanation = explainer.explain(
data=patient_data,
feature_names=feature_names,
num_features=10
)
# Generate report for doctor
report = explanation.to_dict()
print("Contributing factors:")
for feature, weight in report.items():
print(f" {feature}: {weight:.3f}")Fraud Detection System
Identify suspicious transactions and explain why they were flagged as potentially fraudulent.
python
from xgboost import XGBClassifier
from blackbox_core import Explainer
import pandas as pd
# Train fraud detection model
model = XGBClassifier()
model.fit(X_train, y_train)
# Create explainer
explainer = Explainer(model, method='shap')
# Analyze flagged transaction
flagged_transaction = pd.DataFrame({...})
explanation = explainer.explain(
data=flagged_transaction,
feature_names=flagged_transaction.columns.tolist()
)
# Get fraud indicators
fraud_score = model.predict_proba(flagged_transaction)[0][1]
print(f"Fraud probability: {fraud_score:.2%}")
# Show suspicious features
explanation.plot()
# Alert with explanation
alert_message = f"""
Transaction flagged for review (Risk: {fraud_score:.2%})
Top suspicious indicators:
{explanation.get_top_features(n=3)}
"""
print(alert_message)Customer Churn Prediction
Predict customer churn and understand the key factors to enable proactive retention strategies.
python
from lightgbm import LGBMClassifier
from blackbox_core import Explainer
# Train churn model
model = LGBMClassifier()
model.fit(X_train, y_train)
# Create explainer
explainer = Explainer(model, method='shap')
# Identify at-risk customers
at_risk_customers = X_test[model.predict_proba(X_test)[:, 1] > 0.7]
# Get global churn factors
global_explanation = explainer.global_explanation(
data=at_risk_customers,
feature_names=feature_names
)
print("Top churn factors across all at-risk customers:")
global_explanation.plot()
# Explain individual customer
customer_explanation = explainer.explain(
data=at_risk_customers.iloc[0:1],
feature_names=feature_names
)
# Create retention strategy based on explanation
top_factors = customer_explanation.get_top_features(n=3)
print(f"Retention focus areas: {top_factors}")