Scikit-learn
File size: 5,811 Bytes
900087d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Insurance Claims Decision Prediction Script
Provides predictions with required output format
"""

import joblib
import json
import numpy as np
import hashlib
from datetime import datetime

class ClaimsDecisionPredictor:
    def __init__(self, model_path='model_artifacts'):
        """Load model and metadata"""
        self.model = joblib.load(f'{model_path}/claims_decision_model.pkl')
        self.accident_encoder = joblib.load(f'{model_path}/accident_type_encoder.pkl')
        self.police_encoder = joblib.load(f'{model_path}/police_report_encoder.pkl')
        
        with open(f'{model_path}/metadata.json', 'r') as f:
            self.metadata = json.load(f)
    
    def predict(self, claim_data):
        """
        Make prediction with required output format
        
        Args:
            claim_data (dict): Dictionary with keys:
                - claim_amount (float)
                - vehicle_age (int)
                - accident_type (str)
                - police_report (str: 'yes' or 'no')
                - repair_estimate (float)
                - prior_claims (int)
        
        Returns:
            dict: {
                "decision": "<approve|review|reject>",
                "confidence": <0.0-1.0>,
                "top_factors": ["factor_1", "factor_2", "factor_3"]
            }
        """
        # Encode categorical variables
        accident_encoded = self.accident_encoder.transform([claim_data['accident_type']])[0]
        police_encoded = self.police_encoder.transform([claim_data['police_report']])[0]
        
        # Create derived features
        claim_to_estimate_ratio = claim_data['claim_amount'] / (claim_data['repair_estimate'] + 1)
        high_claim_flag = int(claim_data['claim_amount'] > 15000)
        old_vehicle_flag = int(claim_data['vehicle_age'] > 10)
        multiple_claims_flag = int(claim_data['prior_claims'] > 2)
        
        # Prepare feature vector
        features = np.array([[
            claim_data['claim_amount'],
            claim_data['vehicle_age'],
            accident_encoded,
            police_encoded,
            claim_data['repair_estimate'],
            claim_data['prior_claims'],
            claim_to_estimate_ratio,
            high_claim_flag,
            old_vehicle_flag,
            multiple_claims_flag
        ]])
        
        # Get prediction and probabilities
        decision = self.model.predict(features)[0]
        probabilities = self.model.predict_proba(features)[0]
        
        # Get confidence (probability of predicted class)
        decision_idx = list(self.model.classes_).index(decision)
        confidence = float(probabilities[decision_idx])
        
        # Get top factors based on feature importance for this decision
        top_factors = self._get_top_factors(features[0], decision)
        
        return {
            "decision": decision,
            "confidence": round(confidence, 4),
            "top_factors": top_factors
        }
    
    def _get_top_factors(self, feature_values, decision):
        """Extract top 3 factors influencing the decision"""
        decision_idx = list(self.model.classes_).index(decision)
        coefficients = self.model.coef_[decision_idx]
        
        # Calculate contribution of each feature (coefficient * feature_value)
        contributions = np.abs(coefficients * feature_values)
        
        # Get top 3 feature indices
        top_indices = np.argsort(contributions)[-3:][::-1]
        
        # Map to readable feature names
        readable_names = self.metadata['feature_names_readable']
        top_factors = [readable_names[idx] for idx in top_indices]
        
        return top_factors
    
    def predict_with_logging(self, claim_data, log_file='inference_logs.jsonl'):
        """Make prediction and log the inference"""
        prediction = self.predict(claim_data)
        
        # Create log entry
        log_entry = {
            "timestamp": datetime.now().isoformat(),
            "model_version": self.metadata['version'],
            "input_hash": hashlib.md5(json.dumps(claim_data, sort_keys=True).encode()).hexdigest(),
            "decision": prediction['decision'],
            "confidence": prediction['confidence']
        }
        
        # Append to log file
        with open(log_file, 'a') as f:
            f.write(json.dumps(log_entry) + '\n')
        
        return prediction


# Test the predictor
if __name__ == "__main__":
    predictor = ClaimsDecisionPredictor()
    
    # Test case 1: Should approve
    test_claim_1 = {
        "claim_amount": 3500.0,
        "vehicle_age": 3,
        "accident_type": "collision",
        "police_report": "yes",
        "repair_estimate": 3200.0,
        "prior_claims": 0
    }
    
    # Test case 2: Should review
    test_claim_2 = {
        "claim_amount": 12000.0,
        "vehicle_age": 8,
        "accident_type": "theft",
        "police_report": "no",
        "repair_estimate": 8000.0,
        "prior_claims": 2
    }
    
    # Test case 3: Should reject
    test_claim_3 = {
        "claim_amount": 25000.0,
        "vehicle_age": 15,
        "accident_type": "vandalism",
        "police_report": "no",
        "repair_estimate": 5000.0,
        "prior_claims": 5
    }
    
    print("="*60)
    print("TESTING CLAIMS DECISION PREDICTOR")
    print("="*60)
    
    for i, test_claim in enumerate([test_claim_1, test_claim_2, test_claim_3], 1):
        print(f"\nTest Case {i}:")
        print(f"Input: {json.dumps(test_claim, indent=2)}")
        
        result = predictor.predict_with_logging(test_claim)
        print(f"\nPrediction:")
        print(json.dumps(result, indent=2))
        print("-"*60)
    
    print("\n✅ Prediction tests complete!")
    print("Logs saved to: inference_logs.jsonl")