| 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, |
| 'num_conditions': 0.15, |
| 'num_medications': 0.1 |
| } |
|
|
| 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. |
| """ |
| |
| |
| try: |
| model = joblib.load(model_path) |
| return model |
| except: |
| |
| 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: |
| |
| return 0.8 |
| else: |
| |
| |
| 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]]) |
| |
| prob = model.predict_proba(X)[0,1] |
| return float(prob) |
|
|
| |
| if __name__ == "__main__": |
| |
| logging.basicConfig(level=logging.INFO, |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| |
| print("==== Discharge Guard Readmission Risk Prediction Demo ====") |
| |
| |
| 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 |
| } |
| ] |
| |
| |
| print("\n1. Testing SimpleReadmissionModel:") |
| simple_model = SimpleReadmissionModel() |
| |
| |
| 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: |
| from sklearn.ensemble import RandomForestClassifier |
| from sklearn.datasets import make_classification |
| |
| print("\n2. Creating sample RandomForest model for demonstration:") |
| |
| X, y = make_classification(n_samples=1000, n_features=3, |
| n_informative=3, n_redundant=0, |
| random_state=42) |
| |
| |
| rf_model = RandomForestClassifier(n_estimators=10, random_state=42) |
| rf_model.fit(X, y) |
| |
| |
| model_path = "model.joblib" |
| joblib.dump(rf_model, model_path) |
| print(f" Sample model created and saved to {model_path}") |
| |
| |
| 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.") |
|
|