File size: 5,562 Bytes
5a48f8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04c32d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import logging
import pickle
from typing import Dict, Any, Union, Optional
import numpy as np
import joblib

logger = logging.getLogger(__name__)

class SimpleReadmissionModel:
    """
    A simple model for predicting hospital readmission risk
    Can be replaced with a more sophisticated ML model
    """
    
    def __init__(self):
        """Initialize the readmission risk model"""
        self.feature_weights = {
            'age': 0.02,              # Higher age increases risk slightly
            'num_conditions': 0.15,   # More conditions increase risk
            'num_medications': 0.1    # More medications increase risk
        }

    def predict(self, features: Dict[str, Any]) -> float:
        """
        Predict readmission risk based on input features
        :param features: Dictionary of input features
        :return: Predicted readmission risk score
        """
        risk_score = 0.0
        for feature, weight in self.feature_weights.items():
            risk_score += features.get(feature, 0) * weight
        return risk_score

def load_model(model_path="model.joblib"):
    """
    Load a pre-trained model from disk (Joblib, Pickle, or any format).
    For hackathon demonstration, you can store a simple logistic regression or XGBoost model.
    """
    # For now, let's assume you've already trained a model and saved it as model.joblib
    # If you don't have a real model, you could mock or return None.
    try:
        model = joblib.load(model_path)
        return model
    except:
        # If no real model is available, just return None or a dummy object
        print("Warning: No real model found. Using mock predictions.")
        return None

def predict_readmission_risk(model, patient_data: dict) -> float:
    """
    Given patient_data (dict) and a loaded model, return a risk score [0,1].
    If model is None, return a random or fixed value for demonstration.
    """
    if model is None:
        # Mock for demonstration
        return 0.8  # always return 80% risk
    else:
        # Example feature extraction
        # Suppose your model expects [age, num_conditions, num_medications]
        age = patient_data.get('age', 50)
        num_conditions = patient_data.get('num_conditions', 2)
        num_medications = patient_data.get('num_medications', 5)

        X = np.array([[age, num_conditions, num_medications]])
        # If it's a classifier with predict_proba
        prob = model.predict_proba(X)[0,1]
        return float(prob)

# Add this main function
if __name__ == "__main__":
    # Set up logging
    logging.basicConfig(level=logging.INFO, 
                        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    print("==== Discharge Guard Readmission Risk Prediction Demo ====")
    
    # Create test patient data
    test_patients = [
        {
            "id": "P001",
            "name": "John Doe",
            "age": 45,
            "num_conditions": 1,
            "num_medications": 2
        },
        {
            "id": "P002",
            "name": "Jane Smith",
            "age": 72,
            "num_conditions": 4,
            "num_medications": 7
        },
        {
            "id": "P003",
            "name": "Bob Johnson",
            "age": 65,
            "num_conditions": 3,
            "num_medications": 5
        }
    ]
    
    # Create an instance of the SimpleReadmissionModel
    print("\n1. Testing SimpleReadmissionModel:")
    simple_model = SimpleReadmissionModel()
    
    # Test with each patient
    for patient in test_patients:
        risk_score = simple_model.predict(patient)
        risk_percent = risk_score * 100
        print(f"  Patient {patient['id']} ({patient['name']}): Risk Score = {risk_percent:.1f}%")
    
    # Try to create and save a sample model for demonstration
    try:
        from sklearn.ensemble import RandomForestClassifier
        from sklearn.datasets import make_classification
        
        print("\n2. Creating sample RandomForest model for demonstration:")
        # Generate synthetic data
        X, y = make_classification(n_samples=1000, n_features=3, 
                                  n_informative=3, n_redundant=0, 
                                  random_state=42)
        
        # Create and fit a simple model
        rf_model = RandomForestClassifier(n_estimators=10, random_state=42)
        rf_model.fit(X, y)
        
        # Save the model
        model_path = "model.joblib"
        joblib.dump(rf_model, model_path)
        print(f"  Sample model created and saved to {model_path}")
        
        # Now load and use the model
        loaded_model = load_model(model_path)
        
        print("\n3. Testing loaded model predictions:")
        for patient in test_patients:
            risk_score = predict_readmission_risk(loaded_model, patient)
            risk_percent = risk_score * 100
            print(f"  Patient {patient['id']} ({patient['name']}): Risk Score = {risk_percent:.1f}%")
            
    except ImportError:
        print("\nSkipping sklearn model creation (sklearn not available).")
        print("Using dummy prediction function instead:")
        
        for patient in test_patients:
            risk_score = predict_readmission_risk(None, patient)
            risk_percent = risk_score * 100
            print(f"  Patient {patient['id']} ({patient['name']}): Risk Score = {risk_percent:.1f}%")

    print("\nDemo complete. Implement this model in your discharge workflow to identify high-risk patients.")