Integration in das Datenökosystem (Das 'Wo')
Integrationsmethodik der SHAP-Pipeline mit Observability-Plattformen wie Grafana und dem vereinheitlichten Gemini SDK für automatisierte Diagnosen in Portelcore.
4.1. Der analytische Tugendkreis in Portelcore
Sección titulada «4.1. El Círculo Virtuoso Analítico en Portelcore»Der ultimative Wert der Interpretierbarkeit durch SHAP liegt nicht nur in der passiven Erfassung von Telemetriedaten, sondern in ihrer dynamischen Integration zur Optimierung geschäftlicher Entscheidungen.
graph TD A["1. Inferencia & Telemetría<br>(Calcular Predicciones & SHAP)"] --> B["2. Almacenamiento Selectivo<br>(PostgreSQL / SQLite Indexado)"] B --> C["3. Observabilidad & BI<br>(Grafana / Looker Studio)"] C --> D["4. Diagnóstico por IA<br>(Gemini SDK Forensics)"] D --> E["5. Optimización del Modelo<br>(Refactorización de Features)"] E --> A 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 style E fill:#81a1c1,stroke:#5e81ac,stroke-width:1px,color:#2e34404.2. Observability-Dashboards: Verbindung mit Grafana
Sección titulada «4.2. Dashboards de Observabilidad: Conexión con Grafana»Das relationale Schema der analytischen Telemetrie ist ideal, um interaktive Dashboards zu speisen, mit denen das Verhalten und die Gesundheit des Modells überwacht werden können.
1. Panel für Rückverfolgbarkeit und Attributionsverlauf (Liniendiagramm)
Sección titulada «1. Panel de Trazabilidad e Historial de Atribución (Gráfico de Líneas)»- Zweck: Überwachung, ob die Auswirkung einer spezifischen Geschäftsvariablen (z. B.
tickets_soporte_abiertos) im Laufe der Zeit drastisch schwankt. - SQL-Abfrage für Grafana:
SELECTp.predicted_at AS "time",a.shap_value AS "Valor SHAP: Tickets Soporte"FROM model_predictions pJOIN shap_attributions a ON p.prediction_id = a.prediction_idWHERE a.feature_name = 'tickets_soporte_abiertos'AND p.portel_user_id = $portel_user_idORDER BY p.predicted_at ASC;
2. Forensisches Panel für prädiktive Abweichungen (Kontrolltabelle)
Sección titulada «2. Panel Forense de Desvíos Predictivos (Tabla de Control)»- Zweck: Anzeige der Aufschlüsselung von Vorhersagen, bei denen das Modell mit der größten Fehlermarge gescheitert ist.
- SQL-Abfrage für Grafana:
SELECTp.predicted_at AS "Fecha",p.portel_user_id AS "Usuario",p.output_probability AS "Probabilidad Predicha",a.feature_name AS "Variable",a.feature_value AS "Valor Observado",a.shap_value AS "Contribución SHAP"FROM model_predictions pJOIN shap_attributions a ON p.prediction_id = a.prediction_idWHERE p.actual_outcome IS NOT NULLAND (p.output_probability > 0.5) != p.actual_outcome -- DiscordanciaORDER BY ABS(a.shap_value) DESCLIMIT 20;
4.3. Automatisierte forensische Diagnose mit Gemini
Sección titulada «4.3. Diagnóstico Forense Automatizado con Gemini»Die höchste Stufe der analytischen Automatisierung in Portelcore besteht darin, die künstliche Intelligenz von Google (Gemini) zu nutzen, um die logischen Fehler des durch SHAP interpretierten prädiktiven Modells zu prüfen und zu diagnostizieren.
Automatisierungsskript: analisis_forense_ia.py
Sección titulada «Script de Automatización: analisis_forense_ia.py»Dieses Skript interagiert mit der Telemetry-Datenbank und verwendet die einheitliche Google GenAI-SDK (google-genai) zur Generierung strukturierter, natürlichsprachlicher Diagnosen.
import osimport sqlite3from google import genaifrom google.genai import types
# Inicialización segura del cliente unificado de Gemini API# Recuerda exportar la variable de entorno: export GEMINI_API_KEY="tu_clave_de_pruebas"client = genai.Client()
def generar_diagnostico_forense(prediction_id: str) -> str: """ Extrae las atribuciones SHAP de una predicción errónea y genera un diagnóstico detallado utilizando Gemini 2.5 Flash. """ # Conexión a la base de datos local conn = sqlite3.connect("data/portel_telemetry.db") cursor = conn.cursor()
# 1. Obtener detalles de la predicción cursor.execute(""" SELECT portel_user_id, output_probability, actual_outcome FROM model_predictions WHERE prediction_id = ? """, (prediction_id,)) pred_info = cursor.fetchone()
if not pred_info: return "ID de predicción no encontrado."
user_id, prob, actual = pred_info
# 2. Obtener atribuciones SHAP cursor.execute(""" SELECT feature_name, feature_value, shap_value FROM shap_attributions WHERE prediction_id = ? ORDER BY ABS(shap_value) DESC """, (prediction_id,)) attributions = cursor.fetchall() conn.close()
# 3. Construir el prompt analítico desglose_txt = "" for feat, val, shap in attributions: desglose_txt += f"- {feat}: Valor Observado = {val:.2f}, Contribución SHAP = {shap:+.4f}\n"
prompt = f""" Actúa como un experto Ingeniero de Machine Learning y Analista Cuantitativo en Portelcore. Debemos auditar un fallo lógico en nuestro modelo de predicción de abandono (Churn) 'portel_user_churn'.
DETALLES DE LA PREDICCIÓN: - ID Predicción: {prediction_id} - ID Usuario: {user_id} - Probabilidad Predicha por el Modelo: {prob:.4f} (Umbral de decisión > 0.5) - Resultado Real: {'Abandono' if actual else 'Permanencia'} - Estado de Predicción: FALLIDO (El modelo predijo {'Abandono' if prob > 0.5 else 'Permanencia'}, pero ocurrió lo contrario)
CONTRIBUCIONES DETALLADAS DE SHAP: {desglose_txt}
TAREA: 1. Realiza una autopsia técnica del error. Explica por qué el modelo se equivocó basándote en las contribuciones de SHAP. 2. Determina si el modelo confió excesivamente en variables sesgadas o de ruido. 3. Recomienda acciones correctivas de ingeniería de datos para este usuario o para reentrenar el modelo en portelcore.com. """
# 4. Invocación al SDK unificado de Gemini response = client.models.generate_content( model='gemini-2.5-flash', contents=prompt, config=types.GenerateContentConfig( temperature=0.2, # Baja temperatura para análisis consistentes y precisos ) )
return response.text
# Demostración práctica de invocación en laboratorioif __name__ == "__main__": prediction_test_id = "pred_user_17222_40_231" print("--- Iniciando Análisis Forense de Telemetría con Gemini ---") try: diagnostico = generar_diagnostico_forense(prediction_test_id) print("\nDIAGNÓSTICO ENVIADO POR GEMINI API:") print(diagnostico) except Exception as e: print(f"Error en la llamada al SDK GenAI: {e}")4.4. Checkliste zur Ökosystem-Validierung
Sección titulada «4.4. Checklist de Validación del Ecosistema»Stellen Sie sicher, dass die Integration durchgängig funktioniert, bevor Sie die Pipeline abschließen:
- Grafana-Abfragen sind indexiert, um vollständige Tabellenscans der
portelcore.com-Datenbanken zu vermeiden. ✓ - Das Skript
analisis_forense_ia.pyverwendet ausschließlich das Unified SDKgoogle-genai(genai.Client()). ✓ - Die Temperatur des generativen Gemini-Modells ist konservativ ($0,2$) eingestellt, um analytische Halluzinationen in der Produktion zu vermeiden. ✓

