Building a Binary Classifier for Clinical Risk Prediction
Machine LearningModel answerLast updated
Design and implement a complete machine learning pipeline to predict a binary medical outcome from tabular patient data.
You have a dataset of patient records with clinical measurements and a binary outcome indicating whether each patient developed a cardiovascular condition. The dataset includes features such as age, height, weight, blood pressure readings, cholesterol levels, smoking history, and similar health indicators.
Your task is to build a complete machine learning workflow in Python using pandas, scikit-learn, and visualization libraries. Demonstrate how you would:
- Load the data and perform an initial inspection to understand its structure and quality
- Identify and address data quality issues including missing values, duplicates, and physiologically implausible measurements
- Conduct exploratory analysis to understand feature distributions and their relationship to the outcome
- Create derived features that might improve predictive power
- Build and validate a baseline binary classification model using appropriate train/test methodology
- Select and compute evaluation metrics suitable for this problem domain
- Discuss what additional validation steps would be necessary before deploying such a model in a healthcare setting
Assume you have access to standard Python data science and machine learning libraries. Focus on demonstrating sound ML practices, particularly around data leakage prevention, appropriate metric selection for imbalanced medical problems, and handling of missing clinical data.
Hints
Hint 1
Consider which metrics matter most when false negatives and false positives have different real-world costs in medical screening
Hint 2
Imputation parameters must be learned from training data only to avoid leakage—structure your code to enforce this
Hint 3
Clinical measurements have known physiologically valid ranges; use these to detect measurement errors rather than silently accepting outliers
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Building a Binary Classifier for Clinical Risk Prediction: Model Answer
This problem tests your ability to execute a complete applied machine learning workflow with careful attention to data quality, leakage prevention, and domain-appropriate evaluation. The interviewer wants to see structured thinking about messy real-world data and awareness of what makes medical ML different from generic classification tasks.
1. Initial Data Inspection
Start by loading the data and understanding its basic properties:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
data = pd.read_csv("patients.csv")
data.info() # Check column types and null counts
data.describe(include="all").T # Summary statistics
data["outcome"].value_counts(normalize=True) # Class distribution
data.isnull().sum().sort_values(ascending=False) # Missing data patterns
Key questions to answer:
- What is the class balance? If 5% of patients are positive, a 95% accuracy baseline is trivial
- Are numeric columns correctly parsed? String placeholders like "unknown" or "?" may have caused pandas to read numbers as objects
- What are the measurement units? Height could be in meters or centimeters; this affects feature engineering
- Do any columns suggest data leakage? Variables like "prescribed_heart_medication" or "cardiology_visit" may be recorded after diagnosis
2. Data Cleaning Strategy
Handle quality issues systematically:
# Convert placeholder strings to proper missing values
data = data.replace({"?": np.nan, "unknown": np.nan, "": np.nan})
# Parse numeric columns that may have been read as strings
numeric_features = ["age", "height_cm", "weight_kg", "systolic_bp",
"diastolic_bp", "cholesterol_mg_dl"]
data[numeric_features] = data[numeric_features].apply(
pd.to_numeric, errors="coerce"
)
# Remove duplicate records (use patient ID if available)
if "patient_id" in data.columns:
data = data.drop_duplicates(subset="patient_id", keep="first")
else:
data = data.drop_duplicates()
# Flag physiologically impossible values as missing
valid_ranges = {
"age": (18, 110),
"height_cm": (120, 240),
"weight_kg": (30, 300),
"systolic_bp": (70, 260),
"diastolic_bp": (40, 160),
"cholesterol_mg_dl": (80, 600)
}
for column, (lower, upper) in valid_ranges.items():
if column in data.columns:
invalid_mask = ~data[column].between(lower, upper)
data.loc[invalid_mask, column] = np.nan
# Blood pressure consistency check
bp_invalid = data["diastolic_bp"] >= data["systolic_bp"]
data.loc[bp_invalid, ["systolic_bp", "diastolic_bp"]] = np.nan
# Must not lose outcome labels
data = data.dropna(subset=["outcome"])
Critical point: Do not impute yet. Imputation must happen inside the modeling pipeline using only training data to avoid leakage. At this stage, convert invalid values to NaN and preserve them.
3. Exploratory Data Analysis
Visualize feature-target relationships:
# Distribution differences by outcome
for feature in numeric_features:
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
sns.boxplot(data=data, x="outcome", y=feature, ax=axes[0])
sns.kdeplot(data=data, x=feature, hue="outcome",
common_norm=False, ax=axes[1])
plt.tight_layout()
plt.show()
# Correlation analysis
corr_matrix = data[numeric_features + ["outcome"]].corr()
sns.heatmap(corr_matrix, annot=True, cmap="coolwarm", center=0)
# Categorical feature analysis
for cat_col in data.select_dtypes(exclude="number").columns:
if cat_col != "outcome":
sns.barplot(data=data, x=cat_col, y="outcome")
plt.xticks(rotation=45)
plt.show()
Look for:
- Separation power: Which features show clear distribution shifts between positive and negative cases?
- Non-linear relationships: U-shaped or threshold effects suggest binning or tree-based models
- Multicollinearity: Highly correlated features (systolic/diastolic BP, weight/BMI) affect coefficient interpretation
- Suspicious perfect predictors: These almost always indicate leakage
4. Feature Engineering
Create clinically meaningful derived features:
# Body Mass Index
data["bmi"] = data["weight_kg"] / (data["height_cm"] / 100) ** 2
# Pulse pressure (cardiovascular risk indicator)
data["pulse_pressure"] = data["systolic_bp"] - data["diastolic_bp"]
# Clinical threshold flags
data["is_hypertensive"] = (
(data["systolic_bp"] >= 140) |
(data["diastolic_bp"] >= 90)
).astype(float)
data["high_cholesterol"] = (
data["cholesterol_mg_dl"] >= 240
).astype(float)
# Age group binning (risk increases non-linearly with age)
data["age_group"] = pd.cut(
data["age"],
bins=[0, 40, 55, 70, 120],
labels=["<40", "40-54", "55-69", "70+"]
)
These features capture domain knowledge that a linear model cannot learn from raw inputs alone.
5. Baseline Model with Proper Cross-Validation
Build a pipeline that prevents leakage:
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
# Separate features and target
X = data.drop(columns=["outcome", "patient_id"], errors="ignore")
y = data["outcome"].astype(int)
# Identify column types
numeric_cols = X.select_dtypes(include="number").columns.tolist()
categorical_cols = X.select_dtypes(exclude="number").columns.tolist()
# Preprocessing pipeline
preprocessor = ColumnTransformer([
("numeric", Pipeline([
("imputer", SimpleImputer(strategy="median", add_indicator=True)),
("scaler", StandardScaler())
]), numeric_cols),
("categorical", Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("encoder", OneHotEncoder(handle_unknown="ignore", sparse_output=False))
]), categorical_cols)
])
# Model pipeline
model_pipeline = Pipeline([
("preprocessing", preprocessor),
("classifier", LogisticRegression(
C=1.0,
max_iter=1000,
class_weight="balanced",
random_state=42
))
])
# Train/test split with stratification
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
# Cross-validation on training data
cv_strategy = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_results = cross_validate(
model_pipeline,
X_train,
y_train,
cv=cv_strategy,
scoring=["roc_auc", "average_precision", "recall", "precision"],
return_train_score=True
)
print(f"CV ROC-AUC: {cv_results['test_roc_auc'].mean():.3f} ± {cv_results['test_roc_auc'].std():.3f}")
print(f"CV PR-AUC: {cv_results['test_average_precision'].mean():.3f}")
Key practices:
- Preprocessing fits on training folds only within each CV split
- Stratification maintains class balance across folds
- Test set is held out and evaluated once at the end
class_weight="balanced"addresses class imbalance
6. Evaluation for Medical Applications
from sklearn.metrics import (
roc_auc_score, average_precision_score,
classification_report, confusion_matrix,
roc_curve, precision_recall_curve
)
# Fit final model and get predictions
model_pipeline.fit(X_train, y_train)
y_pred_proba = model_pipeline.predict_proba(X_test)[:, 1]
# Threshold-independent metrics
print(f"ROC-AUC: {roc_auc_score(y_test, y_pred_proba):.3f}")
print(f"PR-AUC: {average_precision_score(y_test, y_pred_proba):.3f}")
# Choose threshold based on desired sensitivity/specificity tradeoff
# For screening: prioritize sensitivity (catch most positive cases)
threshold = 0.25 # Determined from validation data
y_pred = (y_pred_proba >= threshold).astype(int)
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# Visualize tradeoffs
fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
plt.plot(fpr, tpr, label=f"Model (AUC={roc_auc_score(y_test, y_pred_proba):.2f})")
plt.plot([0, 1], [0, 1], 'k--', label="Random")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.legend()
plt.show()
Metric selection rationale:
- ROC-AUC: Measures ranking quality across all thresholds; good for comparing models
- PR-AUC: Better than ROC-AUC for imbalanced datasets; emphasizes performance on the minority class
- Sensitivity (Recall): Critical for screening—missing sick patients is costly
- Specificity: Controls false alarms and unnecessary interventions
- Choose threshold based on clinical context: Screening tools prioritize sensitivity; diagnostic tools balance both
Avoid relying on accuracy alone—it is misleading when classes are imbalanced.
7. Pre-Deployment Validation Considerations
Before using this model clinically:
Subgroup analysis: Evaluate performance across demographic groups (age, sex, race) to detect fairness issues and ensure the model works for all patient populations.
Temporal validation: Test on data from a later time period to check if the model degrades as clinical practices or patient populations change.
External validation: Evaluate on data from different hospitals or health systems to assess generalizability.
Calibration check: Use calibration plots to verify that predicted probabilities match actual outcome rates—a 30% prediction should correspond to 30% true positive rate.
Clinical integration: Work with clinicians to understand how predictions will be used, what decision support is needed, and what threshold makes sense for the intended use case.
Interpretability: Use SHAP values or feature importance to explain individual predictions and build trust with clinical users.
Monitoring plan: Define metrics to track in production (prediction distribution, performance drift, missing data rates) and establish a retraining cadence.
Common Mistakes to Avoid
- Imputing with full-dataset statistics before splitting (leakage)
- Ignoring class imbalance and reporting only accuracy
- Not holding out a true test set
- Feature engineering that uses information from the target or future data
- Failing to account for the different costs of false positives vs. false negatives in medical settings
- Overcomplicating the first model—start simple, then iterate
This workflow demonstrates the fundamentals: clean data carefully, prevent leakage, choose appropriate metrics, and think critically about deployment context.