<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Healthcare AI Lab]]></title><description><![CDATA[Healthcare AI Lab]]></description><link>https://healthcareailab.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6a2d73a057e8c25c50b85c3c/e3f959ba-2a48-4b56-992f-653ff0077c01.png</url><title>Healthcare AI Lab</title><link>https://healthcareailab.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 20 Nov 2026 14:57:33 GMT</lastBuildDate><atom:link href="https://healthcareailab.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How I Built an Explainable AI Dashboard to Predict Hospital Readmissions — and Fixed a Python 3.14 Deployment Nightmare]]></title><description><![CDATA[Built a machine learning dashboard to predict hospital readmissions using Explainable AI, Streamlit, and Python with 0.91 ROC-AUC.]]></description><link>https://healthcareailab.hashnode.dev/how-i-built-an-explainable-ai-dashboard-to-predict-hospital-readmissions-and-fixed-a-python-3-14-deployment-nightmare</link><guid isPermaLink="true">https://healthcareailab.hashnode.dev/how-i-built-an-explainable-ai-dashboard-to-predict-hospital-readmissions-and-fixed-a-python-3-14-deployment-nightmare</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[healthcare]]></category><category><![CDATA[streamlit]]></category><category><![CDATA[Python]]></category><category><![CDATA[Healthcare AI]]></category><dc:creator><![CDATA[Neeraja Meda]]></dc:creator><pubDate>Sat, 13 Jun 2026 20:45:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/96244761-548b-4efc-8b8e-5b0193dc3366.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>Every year, nearly <strong>1 in 5 Medicare patients</strong> is readmitted to a hospital within 30 days of discharge — costing the U.S. healthcare system an estimated <strong>$26 billion annually</strong>. Many of these readmissions are preventable. The challenge is identifying <em>which patients</em> are at risk before they leave the hospital.</p>
<p>That's the problem I set out to solve.</p>
<p>In this post, I'll walk you through how I built an <strong>Intelligent Patient Readmission Prediction Dashboard</strong> — an end-to-end machine learning system that predicts 30-day hospital readmission risk with <strong>91% ROC-AUC</strong>, explains <em>why</em> each prediction was made using SHAP (SHapley Additive exPlanations), and delivers everything through an interactive Streamlit dashboard deployed on Streamlit Cloud.</p>
<p>By the end of this article, you'll understand:</p>
<ul>
<li><p>How to build and evaluate a clinical ML classifier with Scikit-Learn</p>
</li>
<li><p>Why Explainable AI is non-negotiable in healthcare — and how SHAP delivers it</p>
</li>
<li><p>How to build an interactive analytics dashboard with Streamlit and Plotly</p>
</li>
<li><p>How to deploy to Streamlit Cloud and debug real dependency failures</p>
</li>
</ul>
<p>Let's get into it.</p>
<hr />
<h2>The Problem: Why Readmission Prediction Matters</h2>
<p>Hospital readmission is one of healthcare's most expensive and preventable problems. When a patient is discharged and then returns within 30 days, it often signals that either their condition wasn't fully resolved, their discharge plan was inadequate, or they lacked the post-discharge support they needed.</p>
<p>Since 2012, the U.S. Centers for Medicare &amp; Medicaid Services (CMS) have penalized hospitals with high readmission rates under the <strong>Hospital Readmissions Reduction Program (HRRP)</strong>. This has made predictive modeling not just clinically valuable — but financially critical for hospital administrators.</p>
<p>From an ML perspective, this is a <strong>binary classification problem</strong>: given a patient's demographic data, diagnosis history, length of stay, and other clinical features at discharge, predict whether they will be readmitted within 30 days.</p>
<p>The core challenge is that this dataset is <strong>highly imbalanced</strong> — readmitted patients are a minority. A naive model that always predicts "not readmitted" would appear 80%+ accurate while being clinically useless. Solving this correctly requires deliberate choices around sampling, evaluation metrics, and model selection.</p>
<hr />
<h2>Dataset and Preprocessing</h2>
<h3>The Data</h3>
<p>The project uses a structured tabular clinical dataset with features including:</p>
<ul>
<li><p><strong>Patient demographics</strong>: age group, gender</p>
</li>
<li><p><strong>Admission details</strong>: admission type, discharge disposition, admission source</p>
</li>
<li><p><strong>Clinical history</strong>: number of prior inpatient/outpatient/emergency visits, number of diagnoses</p>
</li>
<li><p><strong>Medication data</strong>: number of medications, whether insulin was prescribed, changes to medication</p>
</li>
<li><p><strong>Lab results</strong>: HbA1c measurement results, glucose serum levels</p>
</li>
<li><p><strong>Diagnosis codes</strong>: primary, secondary, and tertiary ICD-9 codes</p>
</li>
<li><p><strong>Length of stay</strong>: number of days in hospital</p>
</li>
</ul>
<p>The <strong>target variable</strong> is binary: readmitted within 30 days (1) or not (0).</p>
<h3>Handling Missing Values</h3>
<p>Several features had missing values, particularly diagnosis codes and medical specialty. I applied the following strategy:</p>
<pre><code class="language-python">import pandas as pd
import numpy as np

# Replace '?' with NaN (common in clinical datasets)
df.replace('?', np.nan, inplace=True)

# Drop columns with &gt;40% missing values
threshold = 0.4
df = df[df.columns[df.isnull().mean() &lt; threshold]]

# Impute remaining numerical nulls with median
from sklearn.impute import SimpleImputer
num_imputer = SimpleImputer(strategy='median')
df[numerical_cols] = num_imputer.fit_transform(df[numerical_cols])

# Impute categorical nulls with mode
cat_imputer = SimpleImputer(strategy='most_frequent')
df[categorical_cols] = cat_imputer.fit_transform(df[categorical_cols])
</code></pre>
<h3>Encoding and Scaling</h3>
<p>Categorical features were one-hot encoded. Numerical features were standardized using <code>StandardScaler</code> to ensure no single feature dominated due to scale differences.</p>
<pre><code class="language-python">from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

preprocessor = ColumnTransformer(transformers=[
    ('num', StandardScaler(), numerical_cols),
    ('cat', OneHotEncoder(handle_unknown='ignore', sparse_output=False), categorical_cols)
])
</code></pre>
<h3>Addressing Class Imbalance</h3>
<p>The dataset had roughly a <strong>78:22 split</strong> between non-readmitted and readmitted patients. Training directly on this would bias the model toward the majority class.</p>
<p>I used <strong>SMOTE (Synthetic Minority Oversampling Technique)</strong> on the training set only — never on the test set, which would leak information and inflate performance metrics.</p>
<pre><code class="language-python">from imblearn.over_sampling import SMOTE

smote = SMOTE(random_state=42)
X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)
</code></pre>
<blockquote>
<p><strong>Key insight</strong>: Always apply SMOTE <em>after</em> the train/test split, and <em>only</em> to the training data. Applying it before splitting is a form of data leakage that artificially inflates your evaluation metrics.</p>
</blockquote>
<hr />
<h2>Model Development</h2>
<h3>Why Random Forest?</h3>
<p>I evaluated several classifiers — Logistic Regression, Decision Tree, Random Forest, and Gradient Boosting. Random Forest emerged as the best balance of performance, interpretability, and training speed for this dataset size.</p>
<p>Here's the reasoning:</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>Why Considered</th>
<th>Why Chosen / Rejected</th>
</tr>
</thead>
<tbody><tr>
<td>Logistic Regression</td>
<td>Highly interpretable, fast</td>
<td>Underfit on non-linear relationships</td>
</tr>
<tr>
<td>Decision Tree</td>
<td>Easy to explain</td>
<td>High variance, overfit easily</td>
</tr>
<tr>
<td><strong>Random Forest</strong></td>
<td><strong>Handles non-linearity, robust to outliers</strong></td>
<td><strong>Best overall performance — selected</strong></td>
</tr>
<tr>
<td>Gradient Boosting</td>
<td>Often strongest performance</td>
<td>Slower to tune; marginal gain over RF</td>
</tr>
</tbody></table>
<p>Random Forest also aligns well with SHAP — TreeExplainer (SHAP's backend for tree-based models) computes exact Shapley values efficiently for forest models, making the explainability integration seamless.</p>
<h3>Training the Model</h3>
<pre><code class="language-python">from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, GridSearchCV

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Build full pipeline
model_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier(random_state=42, n_jobs=-1))
])

# Hyperparameter tuning
param_grid = {
    'classifier__n_estimators': [100, 200],
    'classifier__max_depth': [None, 10, 20],
    'classifier__min_samples_split': [2, 5],
    'classifier__class_weight': ['balanced']
}

grid_search = GridSearchCV(
    model_pipeline, param_grid, cv=5,
    scoring='roc_auc', n_jobs=-1, verbose=1
)
grid_search.fit(X_train_resampled, y_train_resampled)

best_model = grid_search.best_estimator_
</code></pre>
<p>Using <code>class_weight='balanced'</code> as an additional safeguard against class imbalance, combined with SMOTE, gave the most stable recall scores across cross-validation folds.</p>
<hr />
<h2>Model Evaluation and Results</h2>
<h3>Core Metrics</h3>
<p>After training on the resampled data and evaluating on the held-out test set (which retained the original class distribution):</p>
<table>
<thead>
<tr>
<th>Metric</th>
<th>Score</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Accuracy</strong></td>
<td>89%</td>
</tr>
<tr>
<td><strong>Precision</strong></td>
<td>87%</td>
</tr>
<tr>
<td><strong>Recall</strong></td>
<td>85%</td>
</tr>
<tr>
<td><strong>F1-Score</strong></td>
<td>86%</td>
</tr>
<tr>
<td><strong>ROC-AUC</strong></td>
<td>0.91</td>
</tr>
</tbody></table>
<h3>Interpreting the Metrics for a Clinical Context</h3>
<p>These numbers need clinical interpretation, not just statistical reading.</p>
<p><strong>Recall (85%)</strong> is the most critical metric here. Recall measures how many of the <em>actually readmitted patients</em> we correctly identified. A false negative — predicting "low risk" when the patient will be readmitted — means a high-risk patient is sent home without additional support or follow-up. This is the more dangerous error in a clinical setting. At 85% recall, we correctly flag 85 out of every 100 truly high-risk patients.</p>
<p><strong>Precision (87%)</strong> tells us that when the model says "high risk," it's right 87% of the time. False positives (flagging a low-risk patient as high-risk) result in unnecessary follow-up interventions — costly but not clinically dangerous.</p>
<p><strong>ROC-AUC of 0.91</strong> is perhaps the most meaningful single number: it means the model correctly ranks a readmitted patient above a non-readmitted patient <strong>91% of the time</strong>, regardless of the decision threshold. This makes it robust to the class imbalance problem.</p>
<h3>ROC-AUC Curve</h3>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/63d18add-1bca-4734-8971-4ab13f2b0fd6.png" alt="" style="display:block;margin:0 auto" />

<p><em>The ROC curve plotting True Positive Rate vs. False Positive Rate at all classification thresholds. The closer the curve hugs the top-left corner, the better the model.</em></p>
<h3>Confusion Matrix</h3>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/44038057-097b-4d36-87f8-398d08003828.png" alt="" style="display:block;margin:0 auto" />

<p><em>The confusion matrix reveals the exact breakdown of True Positives, True Negatives, False Positives, and False Negatives on the test set.</em></p>
<hr />
<h2>Explainability with SHAP — Why the Model Decided What It Did</h2>
<h3>The Problem with Black-Box Models in Healthcare</h3>
<p>Imagine you're a physician and an AI system tells you: <em>"This patient has a 78% probability of readmission."</em></p>
<p>Your first question isn't "How accurate is your model?" — it's "<strong>Why?</strong>"</p>
<p>Without an explanation, the prediction is clinically unusable. You cannot intervene on a probability score alone. You need to know: Is it because of their medication regimen? Their number of prior admissions? Their diagnosis? Only then can you take meaningful action — ordering a follow-up call, arranging home care, or adjusting the discharge plan.</p>
<p>This is why <strong>Explainable AI (XAI)</strong> is not a nice-to-have in clinical ML. It's a requirement.</p>
<h3>What is SHAP?</h3>
<p>SHAP — <strong>SHapley Additive exPlanations</strong> — gives us exactly this. Here's the intuition:</p>
<blockquote>
<p><em>Imagine four colleagues contributed to completing a project. SHAP asks: "If we tried every possible combination of who worked on what, how much did each person's contribution change the outcome?" It averages this across all combinations to fairly credit each person.</em></p>
</blockquote>
<p>SHAP does the same for features in a prediction. For every input feature, it asks: <em>"How much does including this feature change the model's output, averaged across all possible subsets of other features?"</em> The result is a <strong>Shapley value</strong> — a fair, mathematically grounded measure of each feature's contribution to that specific prediction.</p>
<p>Importantly, SHAP values are <strong>locally accurate</strong>: the sum of all SHAP values for a prediction equals the difference between that prediction and the model's average prediction. Nothing is hidden or approximated away.</p>
<h3>Integrating SHAP with Scikit-Learn</h3>
<pre><code class="language-python">import shap

# Extract the trained Random Forest from the pipeline
rf_model = best_model.named_steps['classifier']
X_test_transformed = best_model.named_steps['preprocessor'].transform(X_test)

# Use TreeExplainer for fast, exact Shapley values on tree models
explainer = shap.TreeExplainer(rf_model)
shap_values = explainer.shap_values(X_test_transformed)

# shap_values[1] = SHAP values for the positive class (readmitted)
</code></pre>
<h3>SHAP Summary Plot — Global Feature Importance</h3>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/e8453906-04a1-4a4f-9949-bfc3b6aa0fa1.png" alt="" style="display:block;margin:0 auto" />

<p><em>Each dot is one patient. The x-axis shows the SHAP value (impact on readmission probability). Color represents the feature's value — red = high, blue = low. Dots spread far right push predictions toward readmission.</em></p>
<p><strong>Reading the plot</strong>: The features are ranked top-to-bottom by total importance. The top feature — number of prior inpatient visits — shows that patients with more prior admissions (red dots) have a strong rightward shift, meaning they contribute significantly to higher readmission probability. Younger age (blue dots on the age row) also pushed predictions toward higher risk in this dataset.</p>
<h3>SHAP Waterfall Plot — One Patient Explained</h3>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/e919a3bc-f997-436c-a5e3-403f7765cea3.png" alt="" style="display:block;margin:0 auto" />

<p><em>This explains why Patient #1042 received a 76% readmission risk score. Each bar shows how much one feature pushed the prediction up (red) or down (blue) from the baseline average.</em></p>
<p>For this patient:</p>
<ul>
<li><p><strong>4 prior inpatient visits</strong>: +18.2% to readmission probability</p>
</li>
<li><p><strong>Insulin dosage change</strong>: +9.7%</p>
</li>
<li><p><strong>HbA1c &gt; 8%</strong>: +7.3%</p>
</li>
<li><p><strong>Young age (34)</strong>: −6.1% (younger patients tend to recover faster in this dataset)</p>
</li>
<li><p><strong>Short length of stay (2 days)</strong>: −4.2%</p>
</li>
</ul>
<p>A clinician reading this immediately knows: <em>the prior admission history and uncontrolled diabetes markers are driving this patient's risk.</em> That's an actionable insight.</p>
<hr />
<h2>The Streamlit Dashboard</h2>
<p>The entire ML pipeline — data exploration, prediction, explainability, and performance analytics — is packaged into an interactive dashboard built with Streamlit and Plotly.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/f57ceef8-a42b-4c1e-845e-17b124c6ea90.png" alt="" style="display:block;margin:0 auto" />

<p><em>① Patient input form, ② Real-time prediction output with probability gauge, ③ SHAP explanation panel, ④ Navigation sidebar</em></p>
<h3>Dashboard Structure</h3>
<p>The app is organized into four tabs:</p>
<p><strong>Tab 1 — Patient Readmission Predictor</strong> The user fills in patient details (age, number of medications, prior visits, diagnosis codes, etc.) through an interactive form. On clicking "Predict", the model returns:</p>
<ul>
<li><p>A risk label: <strong>High Risk</strong> or <strong>Low Risk</strong></p>
</li>
<li><p>A probability score (e.g., 76.3%)</p>
</li>
<li><p>A SHAP waterfall plot explaining that specific prediction</p>
</li>
</ul>
<pre><code class="language-python">import streamlit as st
import shap
import plotly.graph_objects as go

st.title("Patient Readmission Risk Predictor")

with st.form("patient_form"):
    age = st.selectbox("Age Group", age_groups)
    num_medications = st.slider("Number of Medications", 1, 81, 15)
    num_lab_procedures = st.slider("Number of Lab Procedures", 1, 132, 40)
    prior_inpatient = st.number_input("Prior Inpatient Visits", 0, 21, 0)
    submitted = st.form_submit_button("Predict Readmission Risk")

if submitted:
    input_df = pd.DataFrame([{...}])  # build from inputs
    prediction = best_model.predict(input_df)[0]
    probability = best_model.predict_proba(input_df)[0][1]

    if prediction == 1:
        st.error(f"High Risk — Readmission Probability: {probability:.1%}")
    else:
        st.success(f"Low Risk — Readmission Probability: {probability:.1%}")
</code></pre>
<p><strong>Tab 2 — Data Exploration</strong> Interactive Plotly charts for exploring the dataset: readmission rate by age group, by admission type, by number of medications. Fully filterable. This tab lets clinicians and data analysts understand population-level patterns.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/eb99f33c-e145-4a58-ade0-c7dc7b756d8e.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Tab 3 — Model Performance Analytics</strong> Displays the ROC-AUC curve, confusion matrix, and classification report — all rendered as interactive Plotly figures. This gives stakeholders confidence in the model's reliability before trusting its predictions.</p>
<p><strong>Tab 4 — SHAP Explainability</strong> A dedicated tab for the SHAP summary beeswarm plot, a force plot visualization, and a feature importance bar chart. Users can select any test patient from a dropdown to view their individual SHAP waterfall explanation.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/e97eb049-4d15-426d-a231-5577e3cdeb51.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Deployment on Streamlit Cloud — and the Python 3.14 Error</h2>
<h3>Deploying to Streamlit Cloud</h3>
<p>Streamlit Cloud makes deployment straightforward: connect your GitHub repository, point it to your <code>app.py</code>, and click Deploy. The platform reads your <code>requirements.txt</code> to install dependencies automatically.</p>
<h3>The Error That Stopped Everything</h3>
<p>After pushing to GitHub and triggering the deployment, I was greeted with this in the Streamlit Cloud logs:</p>
<pre><code class="language-plaintext">ERROR: Could not find a version that satisfies the requirement
scikit-learn==1.4.2 (from versions: none)

note: This error originates from a subprocess, and is likely not a
problem with pip but with the package it was trying to install.

AttributeError: module 'importlib._bootstrap' has no attribute
'_handle_fromlist'
</code></pre>
<p>The deployment was running <strong>Python 3.14</strong> (the latest at the time). After two hours of debugging, I traced the issue: <code>scikit-learn 1.4.x</code> uses internal CPython APIs related to <code>importlib</code> that were restructured in Python 3.14. The library simply hadn't been updated to support 3.14 yet.</p>
<h3>The Fix</h3>
<p>I added a <code>.python-version</code> file and updated <code>requirements.txt</code> to pin Python 3.12:</p>
<pre><code class="language-plaintext"># .python-version
3.12
</code></pre>
<pre><code class="language-txt"># requirements.txt
streamlit==1.32.0
scikit-learn==1.4.2
shap==0.44.1
plotly==5.20.0
pandas==2.2.1
numpy==1.26.4
imbalanced-learn==0.12.0
matplotlib==3.8.3
</code></pre>
<p>After pushing this change, the deployment completed in under 3 minutes with zero errors.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/b5d818c2-9ef9-4f37-abc8-71d2cfa2f8c9.png" alt="" style="display:block;margin:0 auto" />


<img src="https://cdn.hashnode.com/uploads/covers/6a2d73a057e8c25c50b85c3c/97875399-8d26-4fa9-9152-1300a8e97d30.png" alt="" style="display:block;margin:0 auto" />

<blockquote>
<p><strong>Lesson</strong>: Never assume the latest Python version is supported by your entire dependency stack. Always check the compatibility matrix of your most complex libraries (scikit-learn, TensorFlow, PyTorch) and pin to a stable, well-tested Python version. At the time of this project, <strong>Python 3.12</strong> was the sweet spot for the scientific Python ecosystem.</p>
</blockquote>
<hr />
<h2>Challenges Faced</h2>
<p><strong>1. Class imbalance</strong> — The most time-consuming challenge. A naive model achieved 81% accuracy by predicting "not readmitted" for everyone. Getting to genuine predictive power required combining SMOTE with <code>class_weight='balanced'</code> and switching the evaluation criterion from accuracy to ROC-AUC.</p>
<p><strong>2. SHAP integration with pipelines</strong> — SHAP's <code>TreeExplainer</code> needs the raw model, not the full Sklearn pipeline. I initially passed the pipeline object and got cryptic shape mismatch errors. The fix was extracting the classifier step (<code>pipeline.named_steps['classifier']</code>) and separately transforming the test data with the preprocessor step before computing SHAP values.</p>
<p><strong>3. Streamlit form state management</strong> — Streamlit reruns the entire script on every interaction. Storing the trained model and SHAP explainer in <code>st.session_state</code> was essential to avoid re-training on every button click, which would have made the app unusably slow.</p>
<p><strong>4. Python 3.14 compatibility</strong> — Documented in detail above. The fix was straightforward once the root cause was identified, but the debugging process reinforced the importance of pinning dependency versions from the start.</p>
<p><strong>5. SHAP plot rendering in Streamlit</strong> — SHAP's default <code>matplotlib</code> plots don't render cleanly in Streamlit without <code>plt.tight_layout()</code> and <code>st.pyplot(fig, clear_figure=True)</code>. Getting the waterfall and beeswarm plots to render without layout bleeding took several iterations.</p>
<hr />
<h2>Lessons Learned</h2>
<p><strong>1. Recall beats accuracy in imbalanced clinical datasets.</strong> Chasing accuracy in a class-imbalanced problem is a trap. I set ROC-AUC as my primary optimization metric from the start and used recall as the secondary check. This kept me honest about whether the model was genuinely learning or just predicting the majority class.</p>
<p><strong>2. Explainability should be designed in, not bolted on.</strong> I initially planned to add SHAP at the end as a "nice-to-have." Integrating it early forced me to choose a model (Random Forest) that works well with <code>TreeExplainer</code>, and shaped how I structured my preprocessing pipeline. XAI-first design produces better systems.</p>
<p><strong>3. Pin your Python version before you deploy anything.</strong> The Python 3.14 failure cost me several hours. My rule now: check compatibility for <code>scikit-learn</code>, <code>numpy</code>, and <code>pandas</code> together — if all three work on a Python version, the rest usually follows.</p>
<p><strong>4. Streamlit's session state is not optional for ML apps.</strong> Any Streamlit app that loads a model or runs expensive computation needs <code>st.session_state</code>. Without it, every UI interaction re-runs everything from scratch.</p>
<p><strong>5. Document your decisions, not just your code.</strong> The most valuable parts of this project aren't the model weights — they're the reasoning behind choosing Random Forest over XGBoost, SMOTE over class weights alone, and Python 3.12 over 3.14. Future-you (and interviewers) will thank you for writing these down.</p>
<hr />
<h2>Limitations and Future Work</h2>
<p>This project is a proof of concept, not a production clinical tool. Important caveats:</p>
<ul>
<li><p><strong>Dataset generalizability</strong>: The model was trained and evaluated on a single dataset. Performance on data from different hospital systems, geographic regions, or time periods may differ significantly. External validation is required before any clinical use.</p>
</li>
<li><p><strong>No EHR integration</strong>: The current system requires manual data entry. A real deployment would need HL7 FHIR API integration to pull patient data directly from Electronic Health Records.</p>
</li>
<li><p><strong>Demographic fairness</strong>: The model has not been audited for performance disparities across demographic subgroups (race, gender, socioeconomic status). Algorithmic fairness analysis is essential before clinical deployment.</p>
</li>
<li><p><strong>Calibration</strong>: The predicted probabilities should be calibrated using Platt scaling or isotonic regression before being interpreted as true clinical probabilities.</p>
</li>
</ul>
<p><strong>Planned improvements</strong>:</p>
<ul>
<li><p>Add real-time prediction via hospital EHR API</p>
</li>
<li><p>Perform fairness auditing with the <code>fairlearn</code> library</p>
</li>
<li><p>Explore calibrated probability outputs using <code>CalibratedClassifierCV</code></p>
</li>
<li><p>Add time-series features (e.g., trend in HbA1c over last 3 visits)</p>
</li>
<li><p>Containerize with Docker for portable deployment</p>
</li>
</ul>
<hr />
<h2>Conclusion</h2>
<p>Building this dashboard taught me that impactful healthcare ML isn't just about model accuracy — it's about trust, transparency, and usability. A model that achieves 91% ROC-AUC but can't explain its decisions is a liability in a clinical environment. A model that can show <em>exactly which features</em> drove each prediction is a tool clinicians can actually use.</p>
<p>The combination of Scikit-Learn for rigorous modeling, SHAP for honest explainability, Plotly for interactive visualization, and Streamlit for rapid deployment gave me everything I needed to build a system that's both technically sound and practically useful.</p>
<p>If you found this useful, the full source code is on <a href="https://github.com/neeru-meda/Patient-Readmission-Prediction">GitHub</a>. Feel free to fork it, open issues, or connect with me on <a href="https://www.linkedin.com/in/neeraja-meda-aba31b297">LinkedIn</a>.</p>
<p><strong>What would you add to this dashboard?</strong> Drop your thoughts in the comments below.</p>
<hr />
<h2>Tech Stack Summary</h2>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Version</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Python</td>
<td>3.12</td>
<td>Runtime</td>
</tr>
<tr>
<td>Scikit-Learn</td>
<td>1.4.2</td>
<td>ML modeling &amp; preprocessing</td>
</tr>
<tr>
<td>imbalanced-learn</td>
<td>0.12.0</td>
<td>SMOTE oversampling</td>
</tr>
<tr>
<td>SHAP</td>
<td>0.44.1</td>
<td>Explainable AI</td>
</tr>
<tr>
<td>Plotly</td>
<td>5.20.0</td>
<td>Interactive visualizations</td>
</tr>
<tr>
<td>Streamlit</td>
<td>1.32.0</td>
<td>Dashboard &amp; deployment</td>
</tr>
<tr>
<td>Pandas</td>
<td>2.2.1</td>
<td>Data processing</td>
</tr>
<tr>
<td>NumPy</td>
<td>1.26.4</td>
<td>Numerical computing</td>
</tr>
</tbody></table>
<hr />
<p><em>Tags:</em> <code>machine-learning</code> <code>python</code> <code>healthcare</code> <code>data-science</code> <code>streamlit</code></p>
]]></content:encoded></item></channel></rss>