File size: 4,862 Bytes
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
import sqlite3
import numpy as np
import pandas as pd

class ActiveLearningEngine:
    """Identifies and prioritizes high-value samples for human underwriter review and updates reviewer reliability."""
    def __init__(self, db_path):
        self.db_path = db_path
        
    def evaluate_escalation_priority(self, user_profile, dqi_score, ensemble_variance=0.0):
        """Calculates a review priority score (0.0 to 1.0) for a user profile.
        
        Prioritizes:
        - Uncertainty: probability close to decision thresholds (0.1667 for default, 0.35 for stress).
        - OOD: User is OOD/outlier.
        - Ensemble Conflict: High disagreement among sub-models.
        - Fairness Parity: Protected demographic segments (low income, under 25).
        - Low DQI: Low data quality index.
        """
        priority = 0.0
        reasons = []
        
        # 1. Close to threshold (Uncertainty)
        def_prob = user_profile.get("default_probability", 0.0)
        stress_prob = user_profile.get("financial_stress_probability", 0.0)
        
        if 0.10 <= def_prob <= 0.25:
            priority += 0.35
            reasons.append("UNCERTAIN_DEFAULT_PROBABILITY")
        elif 0.30 <= stress_prob <= 0.50:
            priority += 0.25
            reasons.append("UNCERTAIN_STRESS_PROBABILITY")
            
        # 2. Ensemble conflict
        if ensemble_variance > 0.04:
            priority += 0.30
            reasons.append("ENSEMBLE_CONFLICT")
            
        # 3. OOD Trajectories
        ood_alert = user_profile.get("ood_alert", {})
        if ood_alert.get("is_ood", False):
            priority += 0.25
            reasons.append("OOD_BEHAVIORAL_TRAJECTORY")
            
        # 4. Low Data Quality Index (DQI)
        if dqi_score < 0.70:
            priority += 0.20
            reasons.append("LOW_DATA_QUALITY")
            
        # 5. Protected Subgroup Focus (Fairness)
        age = user_profile.get("age", 30)
        income = user_profile.get("gross_income", 3000.0)
        if age < 25 or income < 1200:
            priority += 0.15
            reasons.append("FAIRNESS_SENSITIVE_SUBGROUP")
            
        final_priority = float(np.clip(priority, 0.0, 1.0))
        needs_escalation = final_priority >= 0.50
        
        return {
            "priority_score": round(final_priority, 4),
            "needs_escalation": needs_escalation,
            "escalation_triggers": reasons
        }

    def compute_reviewer_reliability(self, analyst_id):
        """Scores reviewer reliability (0.0 to 1.0) based on long-term outcome consistency.
        
        Compares original model decision and analyst overridden decision to true repayment outcomes.
        If the analyst overrides a model rejection to an approval, and the user defaults, reliability drops.
        If the analyst overrides a model approval to a rejection, and the user's trajectory deteriorates, reliability rises.
        """
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Join human overrides with user repayment outcomes
        query = """
            SELECT ho.new_decision, ho.original_decision, 
                   (SELECT SUM(severity) FROM repayment_outcomes ro WHERE ro.user_id = ho.user_id) AS total_severity
            FROM human_overrides ho
            WHERE ho.analyst_id = ?
        """
        df = pd.read_sql_query(query, conn, params=(analyst_id,))
        conn.close()
        
        if df.empty:
            # Fallback baseline reliability score
            return {
                "analyst_id": analyst_id,
                "reviewer_reliability_index": 0.85,
                "decisions_reviewed": 0,
                "accuracy_rating": "STABLE_DEFAULT"
            }
            
        penalties = 0.0
        n_reviews = len(df)
        
        for idx, row in df.iterrows():
            new_dec = row["new_decision"]
            orig_dec = row["original_decision"]
            severity = row["total_severity"] or 0.0
            
            # Case 1: Override to APPROVED, user defaulted (severity > 0.4)
            if new_dec == "APPROVED" and orig_dec == "REJECTED" and severity > 0.4:
                penalties += 0.15
            # Case 2: Override to REJECTED, user had clean repayment (severity <= 0.0)
            elif new_dec == "REJECTED" and orig_dec == "APPROVED" and severity <= 0.0:
                penalties += 0.05
                
        rri = max(0.40, 1.0 - (penalties / max(1, n_reviews)))
        
        rating = "EXCELLENT" if rri >= 0.90 else "COMPLIANT" if rri >= 0.70 else "RE-TRAINING_REQUIRED"
        
        return {
            "analyst_id": analyst_id,
            "reviewer_reliability_index": float(round(rri, 4)),
            "decisions_reviewed": n_reviews,
            "accuracy_rating": rating
        }