Spaces:
Sleeping
Sleeping
File size: 9,818 Bytes
bc308f6 ff54386 bc308f6 ff54386 bc308f6 ff54386 bc308f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | import os
import sqlite3
import pickle
import json
import datetime
import numpy as np
import pandas as pd
from pathlib import Path
from outcome_learning import ingest_real_outcome
from feature_trust_engine import FeatureTrustEngine
from open_banking_streams import StreamingBankingMonitor
from adaptive_calibration import AdaptiveCalibrationEngine
from macro_adaptation import MacroAdaptationEngine
from human_feedback_learning import HumanFeedbackEngine
from archetype_evolution import ArchetypeEvolutionEngine
from learning_governance import LearningGovernanceGatekeeper
from feature_discovery import FeatureDiscoveryEngine
from active_learning import ActiveLearningEngine
from ensemble_governance import EnsembleGovernance
from external_dataset_registry import ExternalDatasetRegistry
from meta_learning import MetaLearningSystem
class AutonomousLearningEngine:
"""The master orchestrator driving continuous ingestion, real-data prioritization, and scheduler cycles."""
def __init__(self, db_path, models_dir=None):
self.db_path = db_path
if models_dir is None:
self.models_dir = Path(__file__).resolve().parent / "models"
else:
self.models_dir = Path(models_dir)
# Core engines
self.trust_engine = FeatureTrustEngine(db_path)
self.stream_monitor = StreamingBankingMonitor(db_path)
self.calibration_engine = AdaptiveCalibrationEngine(db_path)
self.macro_engine = MacroAdaptationEngine()
self.feedback_engine = HumanFeedbackEngine(db_path)
self.archetype_engine = ArchetypeEvolutionEngine(db_path)
self.gatekeeper = LearningGovernanceGatekeeper(db_path)
self.discovery_engine = FeatureDiscoveryEngine(db_path)
self.active_engine = ActiveLearningEngine(db_path)
self.ensemble_gov = EnsembleGovernance()
self.dataset_registry = ExternalDatasetRegistry()
self.meta_learning = MetaLearningSystem()
# In-memory FSS performance history tracker
self.fss_history = {}
def get_real_data_ratio(self):
"""Calculates real_data_ratio = real_samples / total_samples from DB telemetry."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM repayment_outcomes")
real_samples = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM model_predictions")
pred_samples = cursor.fetchone()[0]
conn.close()
total_samples = real_samples + pred_samples
if total_samples == 0:
return 0.0
return float(real_samples / total_samples)
def calculate_fss(self, feature_name, metrics=None):
"""Computes Feature Survival Score (FSS) based on stability, transfer, and fairness.
FSS = 0.30 * Stability + 0.20 * Transfer + 0.20 * Causal + 0.15 * Drift + 0.15 * Fairness
"""
if metrics is None:
# Default mock parameters representing stable features
stability = np.random.uniform(0.75, 0.95)
transfer = np.random.uniform(0.70, 0.90)
causal = 0.90 if feature_name in ["runway_months", "total_balance", "debt_to_income_ratio"] else 0.60
drift = np.random.uniform(0.80, 0.98)
fairness = np.random.uniform(0.85, 0.98)
# Simulate artificial decay for subscription features
if feature_name in ["subscription_growth_rate", "emergency_borrowing_30d"]:
stability *= 0.35
transfer *= 0.40
drift *= 0.25
else:
stability = metrics.get("stability", 0.80)
transfer = metrics.get("transfer", 0.80)
causal = metrics.get("causal", 0.80)
drift = metrics.get("drift", 0.80)
fairness = metrics.get("fairness", 0.80)
fss = 0.30 * stability + 0.20 * transfer + 0.20 * causal + 0.15 * drift + 0.15 * fairness
fss_clamped = float(np.clip(fss, 0.0, 1.0))
# Log feature performance curve
if feature_name not in self.fss_history:
self.fss_history[feature_name] = []
self.fss_history[feature_name].append(fss_clamped)
return fss_clamped
def run_scheduler_update(self, cycle_type="hourly", context=None):
"""Simulates scheduler micro-updates, recalibrations, retraining, and governance.
Args:
cycle_type (str): 'hourly', 'daily', 'weekly', or 'monthly'
"""
print(f"\n>>> Running Autonomous Scheduler: [{cycle_type.upper()} CYCLE] <<<")
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Base metadata variables
micro_batches = 0
repayments_ingested = 0
recal_triggered = 0
retrain_triggered = 0
gov_passed = True
meta_path = self.models_dir / "model_metadata.pkl"
if not meta_path.exists():
print("Model metadata not found. Skipping cycle.")
conn.close()
return
with open(meta_path, "rb") as f:
meta = pickle.load(f)
feat_names = meta["feature_names"]
model_version = f"xgb_{meta.get('timestamp', 'v1.0')}"
real_ratio = self.get_real_data_ratio()
if cycle_type == "hourly":
# Hourly micro-update: processes streaming telemetry and alerts
micro_batches = 1
print(" - Streaming Open Banking sequence alerts computed.")
elif cycle_type == "daily":
# Daily Recalibration: Evaluates ECE drift and Platt curves
# Measured against observed outcomes only; see the note in
# continuous_learning.py. Fabricated labels previously drove this.
from adaptive_calibration import fetch_matured_calibration_pairs
y_true, y_prob, cal_meta = fetch_matured_calibration_pairs(
self.db_path, model_version=model_version, target="default")
if not cal_meta["sufficient"]:
print(f" [CALIBRATION] Skipped: {cal_meta['reason']}")
else:
cal_report = self.calibration_engine.track_calibration_deterioration(
model_version=model_version,
y_true=y_true,
y_prob=y_prob
)
print(f" [CALIBRATION] Assessed on {cal_meta['matched_pairs']} matured outcomes")
if cal_report["recalibration_triggered"]:
recal_triggered = 1
print(f" - Calibration drift detected! Triggering Platt Recalibration.")
elif cycle_type == "weekly":
# Weekly Retraining & Feature Survival Check
retrain_triggered = 1
print(" - Running Feature Survival Score (FSS) checks...")
# Update FTS suppression states in database for low-scoring features
for feat in feat_names:
fss = self.calculate_fss(feat)
# Log to Feature Trust Logs
status = "ACTIVE"
if fss < 0.45:
status = "SUPPRESSED"
print(f" [SUPPRESSION ALERT] Feature '{feat}' FSS has collapsed to {fss:.4f}! Suppressing runtime influence.")
elif fss < 0.60:
status = "DECAYED"
cursor.execute("""
INSERT INTO feature_trust_logs (
model_version, feature_name, trust_score, stability_score, drift_score, causal_score, status
) VALUES (?, ?, ?, ?, ?, ?, ?)
""", (model_version, feat, fss, fss, fss, fss, status))
# Log run metrics to Meta Learning memory
self.meta_learning.log_meta_run(
model_type="XGBoost_ML",
features_used=feat_names,
ece=0.038,
fgi=0.82,
auc=0.79
)
elif cycle_type == "monthly":
# Monthly Governance: check all gates
print(" - Running monthly safety gate check...")
challenger_metrics = {
"ece": 0.042,
"fgi": 0.81,
"transfer_auc": 0.64,
"psi": 0.08,
"auc": 0.79,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
champion_metrics = {"auc": 0.78}
gate_res = self.gatekeeper.validate_shadow_update(challenger_metrics, champion_metrics)
gov_passed = gate_res["approved"]
print(f" - Safety Gate Verdict: {gate_res['verdict']}. Reasons: {gate_res['reasons']}")
# Log autonomous learning run metadata
run_metadata = {
"cycle_type": cycle_type,
"real_data_ratio": real_ratio,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"notes": f"Completed {cycle_type} continuous cycle update."
}
cursor.execute("""
INSERT INTO autonomous_learning_runs (
micro_batches_processed, repayments_ingested, recalibrations_triggered,
retrainings_triggered, governance_passed, real_data_ratio, metadata
) VALUES (?, ?, ?, ?, ?, ?, ?)
""", (micro_batches, repayments_ingested, recal_triggered, retrain_triggered, 1 if gov_passed else 0, real_ratio, json.dumps(run_metadata)))
conn.commit()
conn.close()
print("Autonomous update logged successfully.")
|