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.")