Spaces:
Sleeping
Sleeping
Download src/drift.py from frigate-global/financial-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 6.24 kB
-
https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/drift.py
- Command line
-
hf download hf://spaces/frigate-global/financial-risk-api/src/drift.py
-
curl -L -o drift.py https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/drift.py
6.24 kB
| import numpy as np | |
| import pandas as pd | |
| from scipy.stats import ks_2samp | |
| from sklearn.metrics import brier_score_loss | |
| def calculate_psi(expected, actual, num_bins=10): | |
| """Calculates the Population Stability Index (PSI) between two distributions. | |
| PSI = sum( (Actual_i - Expected_i) * ln(Actual_i / Expected_i) ) | |
| Interpretation: | |
| PSI < 0.1: No significant distribution change. | |
| 0.1 <= PSI < 0.25: Moderate distribution change. | |
| PSI >= 0.25: Significant distribution change (drift). | |
| """ | |
| expected = np.array(expected) | |
| actual = np.array(actual) | |
| if len(expected) == 0 or len(actual) == 0: | |
| return 0.0, "Empty distribution data." | |
| # Define bins based on expected deciles | |
| percentiles = np.linspace(0, 100, num_bins + 1) | |
| bins = np.percentile(expected, percentiles) | |
| # Deduplicate bins (in case of highly concentrated values) | |
| bins = np.unique(bins) | |
| if len(bins) < 2: | |
| # Fall back to equal width bins if percentiles collide | |
| bins = np.linspace(min(expected.min(), actual.min()), max(expected.max(), actual.max()), num_bins + 1) | |
| bins = np.unique(bins) | |
| # Calculate counts in each bin | |
| expected_counts, _ = np.histogram(expected, bins=bins) | |
| actual_counts, _ = np.histogram(actual, bins=bins) | |
| # Calculate percentages | |
| expected_pct = expected_counts / len(expected) | |
| actual_pct = actual_counts / len(actual) | |
| # Handle zero counts using Laplace-like smoothing | |
| eps = 1e-4 | |
| expected_pct = (expected_pct + eps) / (1.0 + len(expected_pct) * eps) | |
| actual_pct = (actual_pct + eps) / (1.0 + len(actual_pct) * eps) | |
| # Calculate PSI | |
| psi_value = np.sum((actual_pct - expected_pct) * np.log(actual_pct / expected_pct)) | |
| if psi_value < 0.1: | |
| status = "STABLE" | |
| elif psi_value < 0.25: | |
| status = "MODERATE_SHIFT" | |
| else: | |
| status = "DRIFT_DETECTED" | |
| return float(psi_value), status | |
| def check_feature_drift(df_reference, df_target, feature_names): | |
| """Performs Kolmogorov-Smirnov (KS) tests to check for feature distribution shifts. | |
| Returns: | |
| dict: Summary of feature drift, including p-value for each feature. | |
| """ | |
| drift_report = {} | |
| drifted_features_count = 0 | |
| for feat in feature_names: | |
| if feat not in df_reference.columns or feat not in df_target.columns: | |
| continue | |
| ref_data = df_reference[feat].dropna().values | |
| tgt_data = df_target[feat].dropna().values | |
| if len(ref_data) == 0 or len(tgt_data) == 0: | |
| continue | |
| # Run KS test | |
| # H0: The two samples are drawn from the same continuous distribution | |
| stat, p_val = ks_2samp(ref_data, tgt_data) | |
| # If p-value is small (e.g. < 0.05), reject H0 -> Drift detected | |
| is_drifted = p_val < 0.05 | |
| if is_drifted: | |
| drifted_features_count += 1 | |
| drift_report[feat] = { | |
| "ks_statistic": float(stat), | |
| "p_value": float(p_val), | |
| "is_drifted": bool(is_drifted) | |
| } | |
| drift_ratio = drifted_features_count / len(feature_names) if len(feature_names) > 0 else 0.0 | |
| return { | |
| "drift_ratio": drift_ratio, | |
| "drifted_features_count": drifted_features_count, | |
| "feature_details": drift_report | |
| } | |
| def check_calibration_drift(y_true, y_prob, baseline_brier_score, threshold_increase=0.20): | |
| """Checks if Brier score on new labels has deteriorated compared to baseline. | |
| Args: | |
| y_true (array-like): Ground truth outcomes | |
| y_prob (array-like): Model predicted probabilities | |
| baseline_brier_score (float): Brier score at model training/validation | |
| threshold_increase (float): Percentage threshold for drift detection (default 20%) | |
| Returns: | |
| dict: Calibration drift details | |
| """ | |
| y_true = np.array(y_true) | |
| y_prob = np.array(y_prob) | |
| if len(y_true) == 0: | |
| return {"is_drifted": False, "message": "No outcomes available to check calibration."} | |
| current_brier = brier_score_loss(y_true, y_prob) | |
| # Increase in Brier score represents calibration degradation | |
| increase = (current_brier - baseline_brier_score) / max(1e-5, baseline_brier_score) | |
| is_drifted = increase > threshold_increase and current_brier > 0.02 | |
| return { | |
| "baseline_brier_score": float(baseline_brier_score), | |
| "current_brier_score": float(current_brier), | |
| "percentage_increase": float(increase * 100), | |
| "is_drifted": bool(is_drifted) | |
| } | |
| def calculate_js_divergence(expected, actual, num_bins=10): | |
| """Computes the Jensen-Shannon (JS) divergence between two distributions.""" | |
| expected = np.array(expected) | |
| actual = np.array(actual) | |
| if len(expected) == 0 or len(actual) == 0: | |
| return 0.0 | |
| percentiles = np.linspace(0, 100, num_bins + 1) | |
| bins = np.percentile(expected, percentiles) | |
| bins = np.unique(bins) | |
| if len(bins) < 2: | |
| bins = np.linspace(min(expected.min(), actual.min()), max(expected.max(), actual.max()), num_bins + 1) | |
| bins = np.unique(bins) | |
| expected_counts, _ = np.histogram(expected, bins=bins) | |
| actual_counts, _ = np.histogram(actual, bins=bins) | |
| p = expected_counts / len(expected) | |
| q = actual_counts / len(actual) | |
| eps = 1e-5 | |
| p = (p + eps) / (1.0 + len(p) * eps) | |
| q = (q + eps) / (1.0 + len(q) * eps) | |
| m = 0.5 * (p + q) | |
| kl_pm = np.sum(p * np.log2(p / m)) | |
| kl_qm = np.sum(q * np.log2(q / m)) | |
| js_div = 0.5 * kl_pm + 0.5 * kl_qm | |
| return float(js_div) | |
| def check_latent_trajectory_drift(ref_embeddings, target_embeddings): | |
| """Computes mean vector shift on latent sequence representation matrices.""" | |
| ref_embeddings = np.array(ref_embeddings) | |
| target_embeddings = np.array(target_embeddings) | |
| if len(ref_embeddings) == 0 or len(target_embeddings) == 0: | |
| return 0.0 | |
| ref_centroid = np.mean(ref_embeddings, axis=0) | |
| tgt_centroid = np.mean(target_embeddings, axis=0) | |
| shift = np.linalg.norm(ref_centroid - tgt_centroid) | |
| return float(shift) | |