Ir al contenido

Practical Application and Use Cases (The 'How')

Guide to SHAP implementation in Python for Machine Learning models at Portelcore, with key visualizations and business cases.

0views

2.1. SHAP Implementation in Python (The Technical Workflow)

Sección titulada «2.1. Implementación de SHAP en Python (El Flujo Técnico)»

The integration of SHAP into Portelcore's Machine Learning pipelines is extremely elegant and direct thanks to the Python shap library. Below is the standard technical workflow structured in three phases:

graph TD
A["Fase 1: Preparación del Modelo (Entrenamiento)<br>model.fit()"] --> B["Fase 2: Inicialización del Explicador<br>shap.Explainer()"]
B --> C["Fase 3: Computación de Valores SHAP<br>explainer(X_test)"]
C --> D["Fase 4: Renderizado de Visualizaciones<br>(Beeswarm, Force, Bar plots)"]
style A fill:#3b4252,stroke:#4c566a,stroke-width:1px,color:#d8dee9
style B fill:#3b4252,stroke:#4c566a,stroke-width:1px,color:#d8dee9
style C fill:#3b4252,stroke:#4c566a,stroke-width:1px,color:#d8dee9
style D fill:#a3be8c,stroke:#8fbcbb,stroke-width:2px,color:#2e3440

Before invoking the explainer, the estimator must be fully fitted with the tenant's training data.

import xgboost as xgb
from sklearn.model_selection import train_test_split
import pandas as pd
# Carga de datos de usuarios sintéticos de Portelcore
df = pd.read_csv("data/portel_user_churn.csv")
X = df.drop(columns=["user_id", "churned", "domain"])
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Entrenamiento de un clasificador XGBoost de alta precisión
model = xgb.XGBClassifier(eval_metric="logloss", random_state=42)
model.fit(X_train, y_train)

Phase 2: Instantiate the shap.Explainer

Sección titulada «Fase 2: Instanciar el shap.Explainer»

The “Explainer” analyzes the model trees (in the case of XGBoost, it uses the highly optimized TreeExplainer implementation) or the general behavior if it is a generic model.

import shap
# Inicialización optimizada para modelos basados en árboles (Tree SHAP)
explainer = shap.Explainer(model, X_train)

We calculate SHAP values on the test set to exhaustively evaluate the logic applied by the model.

# Carga y computación de los valores SHAP
shap_values = explainer(X_test)

The true analytical power of SHAP lies in its capacity for visual synthesis. The two gold-standard visualization tools implemented in Portelcore are:

The Beeswarm plot summarizes the importance and direction of impact of each feature across the entire dataset.

Visual ComponentTechnical Representation and Reading
Y-Axis SortingVariables are sorted vertically from highest to lowest average predictive impact (magnitude $
X-Axis PositionThe horizontal displacement of a point indicates the SHAP Value. Values to the right ($>0$) increase the probability of the event (e.g., Churn); to the left ($<0$), they reduce it.
Color GradientIndicates the absolute value of the original variable: Red for high attribute values, Blue for low values.
# Ejemplo de Interpretación en Negocio:
"Un volumen de 'tickets_soporte_abiertos' alto (Puntos Rojos) se desplaza masivamente hacia la derecha (SHAP > 0), indicando que el modelo asocia de forma robusta la acumulación de incidencias abiertas con el churn de portel_user."

2. The Force Plot (Local Explanatory Analysis)

Sección titulada «2. El Force Plot (Análisis Explicativo Local)»

The force plot or contribution horizons analyzes a single individual record (a prediction "autopsy").

[Fuerzas Azules: Empujan a la baja] [Fuerzas Rojas: Empujan al alza]
-----------------------------------> <--------------------------------
Latencia Red (-0.12) País Local (-0.08) Tickets Abiertos (+0.35) Sesiones Bajas (+0.22)
|============================= [ Predicción Final: 0.52 ] =============================|
(Valor Base: 0.15)
  • Interaction Logic:
    • Starting from the Base Value ($0.15$), variables with positive contributions (Red) pull the result upwards, while negative ones (Blue) reduce it.
    • The Final Prediction ($0.52$) is the equilibrium point where both forces are quantitatively neutralized.

Our architectures leverage SHAP interpretability across multiple technological units:

  1. Account Governance (portel_user):
    • Identification of early warning alerts for service degradation and subscription cancellations, explaining the exact reason for the churn alert to the Customer Success team.
  2. Security and Anomaly Detection:
    • Explaining risk scores for suspicious access or anomalous network behavior within the portelcore.com domain.
  3. Algorithm Audit (Anti-Bias):
    • Ensure that no variables introduce indirect demographic or racial biases in internal predictive models, complying with current transparent AI legislation.

Complete the validation steps before proceeding to the optimization guide:

  • I have installed the official dependency shap and configured a test virtual environment in portelcore.com. ✓
  • I can train a simple XGBoost model and successfully extract its respective Explainer object without type errors. ✓
  • I know how to correctly interpret the color gradient and the position on the X-axis of a Beeswarm plot. ✓