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.
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:#2e3440Phase 1: Model Training
Sección titulada «Fase 1: Entrenamiento del Modelo»Before invoking the explainer, the estimator must be fully fitted with the tenant's training data.
import xgboost as xgbfrom sklearn.model_selection import train_test_splitimport pandas as pd
# Carga de datos de usuarios sintéticos de Portelcoredf = 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ónmodel = 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)Phase 3: Attribution Generation shap_values
Sección titulada «Fase 3: Generación de Atribuciones shap_values»We calculate SHAP values on the test set to exhaustively evaluate the logic applied by the model.
# Carga y computación de los valores SHAPshap_values = explainer(X_test)2.2. Key Visualizations for Decision Making
Sección titulada «2.2. Visualizaciones Clave para la Toma de Decisiones»The true analytical power of SHAP lies in its capacity for visual synthesis. The two gold-standard visualization tools implemented in Portelcore are:
1. The Beeswarm Plot (Global Analysis)
Sección titulada «1. El Gráfico Beeswarm (Análisis Global)»The Beeswarm plot summarizes the importance and direction of impact of each feature across the entire dataset.
| Visual Component | Technical Representation and Reading |
|---|---|
| Y-Axis Sorting | Variables are sorted vertically from highest to lowest average predictive impact (magnitude $ |
| X-Axis Position | The 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 Gradient | Indicates 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.
2.3. Strategic Use Cases in Portelcore
Sección titulada «2.3. Casos de Uso Estratégicos en Portelcore»Our architectures leverage SHAP interpretability across multiple technological units:
- 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.
- Security and Anomaly Detection:
- Explaining risk scores for suspicious access or anomalous network behavior within the
portelcore.comdomain.
- Explaining risk scores for suspicious access or anomalous network behavior within the
- Algorithm Audit (Anti-Bias):
- Ensure that no variables introduce indirect demographic or racial biases in internal predictive models, complying with current transparent AI legislation.
2.4. Practical Validation Checklist
Sección titulada «2.4. Checklist de Validación Práctica»Complete the validation steps before proceeding to the optimization guide:
- I have installed the official dependency
shapand configured a test virtual environment inportelcore.com. ✓ - I can train a simple XGBoost model and successfully extract its respective
Explainerobject without type errors. ✓ - I know how to correctly interpret the color gradient and the position on the X-axis of a Beeswarm plot. ✓

