Spaces:
Sleeping
Sleeping
Download src/archetype_evolution.py from frigate-global/financial-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 4.5 kB
-
https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/archetype_evolution.py
- Command line
-
hf download hf://spaces/frigate-global/financial-risk-api/src/archetype_evolution.py
-
curl -L -o archetype_evolution.py https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/archetype_evolution.py
4.5 kB
| import os | |
| import sqlite3 | |
| import json | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.cluster import MiniBatchKMeans | |
| ARCHETYPE_LABELS = [ | |
| "Stable Savers", | |
| "Paycheck-to-Paycheck", | |
| "Debt Spiral", | |
| "Volatile Gig Workers", | |
| "Recovering Stress", | |
| "Compulsive Overspenders" | |
| ] | |
| class ArchetypeEvolutionEngine: | |
| """Manages behavioral clustering, tracks archetype centroid drift, and transition probabilities.""" | |
| def __init__(self, db_path, n_clusters=6): | |
| self.db_path = db_path | |
| self.n_clusters = n_clusters | |
| self.clustering_model = MiniBatchKMeans(n_clusters=n_clusters, random_state=42, batch_size=100) | |
| def fit_incremental(self, df_features, feature_cols): | |
| """Fits MiniBatchKMeans incrementally on a streaming batch of user snapshots.""" | |
| X = df_features[feature_cols].values | |
| # Replace NaNs | |
| X = np.nan_to_num(X, nan=0.0) | |
| if X.shape[0] < self.n_clusters: | |
| # Load historical snapshots to ensure batch size is at least n_clusters | |
| conn = sqlite3.connect(self.db_path) | |
| try: | |
| df_all = pd.read_sql_query("SELECT * FROM feature_snapshots", conn) | |
| if not df_all.empty and len(df_all) >= self.n_clusters: | |
| X_all = df_all[feature_cols].values | |
| X_all = np.nan_to_num(X_all, nan=0.0) | |
| X = np.vstack([X_all, X]) | |
| except Exception as e: | |
| print("Warning: could not load historical snapshots for clustering:", e) | |
| finally: | |
| conn.close() | |
| if X.shape[0] >= self.n_clusters: | |
| self.clustering_model.partial_fit(X) | |
| centroids = self.clustering_model.cluster_centers_ | |
| else: | |
| # Fallback to dummy centroids if still not enough data | |
| centroids = np.zeros((self.n_clusters, len(feature_cols))) | |
| # Check for splits/merges | |
| action = "STABLE" | |
| # 1. Merge Check: check pairwise distance between centroids | |
| distances = [] | |
| for i in range(self.n_clusters): | |
| for j in range(i + 1, self.n_clusters): | |
| dist = np.linalg.norm(centroids[i] - centroids[j]) | |
| distances.append((i, j, dist)) | |
| min_dist = min([d[2] for d in distances]) if distances else 999.0 | |
| if min_dist < 0.15: | |
| action = "MERGE" | |
| print(f" [ARCHETYPE EVENT] Potential cluster merge detected (distance: {min_dist:.4f})") | |
| # Log to database | |
| self._log_evolution(centroids.tolist(), ARCHETYPE_LABELS, action) | |
| return centroids, action | |
| def _log_evolution(self, centroids, labels, action): | |
| """Saves archetype snapshots to SQL database table.""" | |
| # Simple identity transition matrix (mock) | |
| trans_matrix = np.eye(self.n_clusters).tolist() | |
| conn = sqlite3.connect(self.db_path) | |
| cursor = conn.cursor() | |
| cursor.execute(""" | |
| INSERT INTO archetype_evolution_logs ( | |
| cluster_centroids, active_archetypes, transition_matrix, action_taken | |
| ) VALUES (?, ?, ?, ?) | |
| """, (json.dumps(centroids), json.dumps(labels), json.dumps(trans_matrix), action)) | |
| conn.commit() | |
| conn.close() | |
| def calculate_transition_rates(self, df_snapshots): | |
| """Computes transition probabilities: probability of users moving from one cluster to another.""" | |
| # Check transition between consecutive snapshots of the same users | |
| df_sorted = df_snapshots.sort_values(["user_id", "snapshot_date"]) | |
| # Mock transition rates based on runway changes | |
| transitions = {label: {l: 0.0 for l in ARCHETYPE_LABELS} for label in ARCHETYPE_LABELS} | |
| # Fill transition matrix diagonal with high probability, minor off-diagonal probabilities | |
| for l1 in ARCHETYPE_LABELS: | |
| for l2 in ARCHETYPE_LABELS: | |
| if l1 == l2: | |
| transitions[l1][l2] = 0.85 | |
| elif (l1 == "Stable Savers" and l2 == "Paycheck-to-Paycheck") or \ | |
| (l1 == "Paycheck-to-Paycheck" and l2 == "Debt Spiral") or \ | |
| (l1 == "Debt Spiral" and l2 == "Recovering Stress"): | |
| transitions[l1][l2] = 0.10 | |
| else: | |
| transitions[l1][l2] = 0.01 | |
| return transitions | |