Overview Data Market Basket Clustering Classification Forecasting Results Findings
Clinical ML  |  Market Basket Analysis  |  Penn State DAAN 888

Market Basket Analysis on Chronic Systolic
Heart Failure Prescribing

A Penn State DAAN 888 capstone applying association rule mining, dimensionality reduction, and time series forecasting to a real IQVIA longitudinal prescription dataset for Chronic Systolic Heart Failure (HFrEF, ICD-10 I50.22, ejection fraction ≤ 40%). Roughly 6.7 million Americans are diagnosed with heart failure annually, about half with reduced ejection fraction. The project started from a simple question, prompted by how many heart-drug TV ads exist: which drugs actually get prescribed together, and what does that pattern reveal about clinical practice, drug clusters, and future prescribing volume?

PythonFP-Growth / Association RulesTruncatedSVD KMeans k=11XGBoostRandom Forest SVMGAN / DTW / TSGM MongoDBHadoop / SparkCassandraPostgreSQL
7,685,672
Transactional rows analyzed
11
Explainable Variance Clusters
96%
Cluster prediction accuracy
94.3%
Drug prediction accuracy
2019–2024
Years of prescribing data
Data Foundation

The IQVIA Prescribing Dataset

The source is IQVIA's longitudinal U.S. prescriber-level dispensing data for Chronic Systolic Heart Failure. Each row in the raw wide-format table is an aggregated count of prescriptions for a unique combination of drug, manufacturer, specialty, age band, gender, and month/year, with a total_count column holding the number of prescriptions. To make the data compatible with market basket analysis, rows are exploded into one transaction per visit — duplicating each row total_count times — which expands the table to 7,685,672 rows × 9 columns.

ColumnTypeScaleExample
Month, YearDateTimeIntervalAugust 2019
Manufacturing CompanyStringCategoricalAccord Healthcare
Drug NameStringCategoricalEplerenone
Type of DrugStringCategoricalAddiction Medicine
Age RangeStringOrdinal65 to 74
GenderStringCategoricalMale
ICD-10 CodeStringConstant, droppedI50.22
Description of DiseaseStringCategoricalChronic Systolic Heart Failure
Number of VisitsIntegerRatio150

Storage & Traversal Architecture

The pipeline is designed to handle over ten million records: raw JSON lands in MongoDB as a schema-less staging area, Hadoop/HDFS and Spark run distributed ETL, curated time-series records move into Cassandra for high-availability writes, a summarized analytical subset is loaded into PostgreSQL for BI querying, and Redis caches frequently-requested aggregates ahead of Power BI dashboards.

Ingest
Data Cube → MongoDB
Raw JSON lands in MongoDB, a schema-less document store used as the staging area for diverse, evolving record structures.
Process
Hadoop + Spark (Docker)
HDFS handles distributed batch storage while Spark runs in-memory ETL; every service is containerized for portability and isolation.
Store
Cassandra
Canonical time-series metrics land here — a peer-to-peer NoSQL store built for high-velocity writes with no single point of failure.
Serve
PostgreSQL + Redis
Aggregated, business-ready data is loaded into PostgreSQL for BI queries; Redis caches hot results ahead of Power BI and the Python/ML layer.
Traversal time distribution on the updated 7,685,672-row dataframe: pandas methods vs PostgreSQL
Traversal benchmark on the full 7,685,672 × 9 dataframe. Vectorized pandas operations complete in ~0.08s — a three-order-of-magnitude improvement over row-by-row iteration. Among iterative methods, itertuples is fastest (~88s median), followed by apply (~115s), iterrows (~228s), and plain index-based for-loops, the worst at ~262s. Querying the same scale through a PostgreSQL cursor lands at a consistent ~37–40s, useful when server-side filtering can reduce what's transferred client-side.
Association Rule Mining

Market Basket Analysis of Co-Prescribed Drugs

Market basket analysis uncovers purchase patterns — here, prescribing patterns — using association rule mining to find drugs that frequently co-occur within the same patient visit. The project set out to answer four questions: which drugs are commonly prescribed together for a given age range and gender; when a specific drug class is prescribed, what other classes accompany it; which competitor products land in the same "basket" for the same underlying condition; and whether similar drugs are prescribed across ostensibly unrelated specialties, such as addiction medicine and cardiology.

Transactional reshaping. Because market basket analysis needs one row per transaction, the aggregated dataset (one row per drug/demographic combination with a total_count) is expanded into one row per individual visit, duplicated total_count times per combination — converting the wide-format table into the 4.5M-row transactional format used for FP-Growth-style association mining.

Top Co-Prescribed Pairs by Year

YearTop PairCo-occurrencesSupportConfidence
2019Carvedilol ↔ Metoprolol Succinate21311.59%44.84%
2020Carvedilol ↔ Metoprolol Succinate56812.82%49.48%
2021Carvedilol ↔ Metoprolol Succinate58413.50%50.87%
2022Carvedilol ↔ Metoprolol Succinate58513.46%46.54%
2023Metoprolol Succinate ↔ Spironolactone54912.53%31.23%
2024Carvedilol ↔ Metoprolol Succinate63014.96%55.17%
All yearsCarvedilol ↔ Metoprolol Succinate1,03418.14%63.79%
Consistent dual beta-blockade. Carvedilol and Metoprolol Succinate are the dominant co-prescribed pair in five of six years, with confidence climbing to 63.79% across the full period — nearly two-thirds of Carvedilol prescriptions include Metoprolol Succinate, consistent with guideline-directed HFrEF therapy.
2023 shift, 2024 SGLT2 emergence. 2023 briefly breaks the pattern with an MRA combination (Metoprolol Succinate + Spironolactone) topping the list. By 2024, Dapagliflozin and Jardiance pairs surface with 28–29% support — consistent with SGLT2 inhibitors' expanded FDA heart-failure indication being adopted in practice roughly two years later.
Dimensionality Reduction & Segmentation

From PCA to t-SNE to TruncatedSVD

Before clustering, categorical fields (drug, manufacturer, specialty, age range, gender) are numerically encoded, and three dimensionality reduction techniques are compared year-over-year to find the one that best preserves structure in this high-dimensional, largely categorical pharmaceutical data.

YearPCA Variance Explainedt-SNE Variance Explained
20190.3010.58
20200.2920.62
20210.3560.47
20220.3990.59
20230.4010.54
20240.3910.55

PCA averages only ~37% variance explained — it captures linear relationships well but misses the fine-grained local structure this categorical data needs. Moving to t-SNE lifts average variance to ~58%, but it fluctuates between 0.47 and 0.62 across years with no stable global representation, making clusters hard to interpret quantitatively. TruncatedSVD resolves both problems: three components capture 80% of total variance, and the resulting space is stable enough to cluster reliably.

3D TruncatedSVD scatter plot with KMeans k=11 clusters
KMeans (k=11) on TruncatedSVD-reduced space. Each point represents a (drug, age range, gender, prescriber specialty, manufacturer) combination, colored by cluster. Clusters 0/1/5/6 occupy the negative-value region and likely share a therapeutic or pharmacokinetic profile; Cluster 2 (bright green) is a dense, well-isolated group in the positive region; Clusters 3/4/7/8/9/10 occupy mixed mid-regions, with some elongated distributions suggesting k=11 may slightly over-segment a few areas.
Supervised Validation

Predicting Clusters, Drugs, and Gender

To validate that the unsupervised clusters were meaningful (not artifacts), an XGBoost classifier was trained to predict cluster membership and drug identity directly from the SVD components. A separate pipeline — Random Forest, SVM, and Gradient Boosting — tests whether prescribing patterns alone (no demographic fields) can predict patient gender.

Confusion matrices for cluster and drug prediction on the updated 7,685,672-row dataset
Cluster prediction: 96% accuracy across 11 explainable-variance clusters. Drug prediction: 94.3% accuracy distinguishing 15 pharmaceutical compounds. Misclassifications concentrate between adjacent clusters and between drugs in the same pharmacological class (ACE inhibitors, ARBs, beta-blockers) — expected given their structural similarity.
Cross-validation learning curve for cluster prediction
Learning curve confirms genuine generalization, not overfitting. Training accuracy holds steady at 0.9996 regardless of sample size. Cross-validation accuracy starts at 0.9987 with 50,000 samples and rises to 0.9994 at 450,000 samples, with the train/validation gap narrowing from 0.0009 to 0.0002 — the model is learning real structure, not memorizing.
SVM decision boundary for gender identification from SVD components
SVM gender decision boundary. Non-linear boundaries partition the SVD-reduced space into coherent regions; most points fall well within their predicted region, indicating high classification confidence.
Random Forest decision tree for gender classification
RF decision tree (depth 5, one of 100). Prescriber is the strongest gender differentiator in both trees — the very first split — with terminal-node gini values near zero, meaning gender is discoverable through fairly simple decision rules from prescribing behavior alone.
Time Series Forecasting

Seven-Stage Forecasting Pipeline with Synthetic Augmentation

Forecasting monthly prescription volume runs into a hard constraint: only a handful of complete annual cycles exist, which starves data-hungry models. Rather than accept that ceiling, the pipeline generates synthetic training data through three different techniques before feature engineering and modeling.

Stage 1
Raw Data
Ingest month/year prescribing records with their native temporal frequency.
Stage 2
Pre-Process
Chronological alignment, gap handling, and conversion to lags and rolling means.
Stage 3
Synthesize (parallel)
GAN, DTW, and TSGM each generate synthetic sequences independently, per split.
Stage 4
Augment Data
Merge synthetic streams with real data into an expanded training corpus.
Stage 5
Feature Engineer
Cyclical month encoding, autoregressive lags, rolling stats, growth/momentum.
Stage 6
Model
Linear (L1/L2), Random Forest, deep learning, and Kalman/ARIMA trained in parallel.
Stage 7
Evaluate
MAE, RMSE, MAPE, and R² across train/test, with residual and leakage checks.

Synthetic data is generated independently per train/validation/test split to avoid leakage — the same principle that caught the linear regression bug in the Results section.

GAN — "Mimic"

A Generator and Discriminator train adversarially until the Generator produces sequences the Discriminator can't distinguish from real data. Flexible and expressive, but training can be unstable (mode collapse, vanishing gradients) and computationally heavy.

DTW — "Time Warping"

Dynamic Time Warping finds the optimal temporal alignment between similar sequences and synthesizes new data by morphing between them. Preserves temporal coherence well, but can only interpolate within the convex hull of existing patterns — limited novelty.

TSGM — "GAN + Encoders"

An Encoder-Decoder-Discriminator architecture with recurrent/attention layers, purpose-built to preserve autocorrelation and seasonality. Generally more stable than a plain GAN, at the cost of added architectural complexity.

Feature engineering converts the cleaned time index into month_sin/month_cos cyclical encodings, lag_1/2/3 autoregressive terms, 3-month rolling mean/std/max, yearly growth, and 1- and 3-month momentum — giving every model family the same seasonal and trend signal to work with.

Model Comparison

Forecasting Results — and an Honest Data Leakage Catch

Four model families were evaluated on both the original and GAN/DTW/TSGM-augmented training data. The most useful result of this section wasn't the best score — it was catching a bad one.

Linear Regression: R² = 1.0000 is a red flag, not a win

The baseline linear/ridge regression achieved a perfect R² of 1.0000 on both training and test sets, with residuals at the 10-10 scale — floating-point noise, not real error. No legitimate model achieves perfect prediction on real-world time series. This is a textbook sign of data leakage: either the target leaked into the features, or the train/test split preserved temporal information it shouldn't have. Rather than reporting this as a strength, the report flags it explicitly as a methodology bug requiring investigation — and excludes it from the model comparison that matters.

Linear regression showing suspicious perfect R-squared, a data leakage indicator
Perfect diagonal alignment in both training and test actual-vs-predicted plots, with residuals at 10-10, confirming the leakage diagnosis visually.
ModelTrain R² (original)Test R² (original)Train R² (augmented)Test R² (augmented)
KNN1.00*~0.141.00*~0.91
Random Forest0.880.790.970.88
XGBoost0.98720.92960.990.97

*KNN's train R² of ~1.0 reflects memorization of training points, not genuine fit — its collapse to ~0.14 test R² on original data confirms it. Augmentation lifts KNN's test score but the residuals stay large and noisy, suggesting it's fitting injected synthetic patterns more than real structure.

Random Forest forecasting results, original and augmented data
Random Forest. Tracks overall trend and scale but smooths local peaks; residuals show a level-dependent bias (under-predicts highs, over-predicts lows). A reasonable baseline, not a final model.
XGBoost forecasting results, original data, the best-performing model
XGBoost — best performer. Test R² of 0.93 (original) rising to 0.97 (augmented), with points tracking tightly along the 45° line and residuals centered near zero. The clear choice for production forecasting.
Summary

Key Findings

Dominant Co-Prescription

Carvedilol + Metoprolol Succinate is the top co-prescribed pair in five of six years (confidence 45–55%, reaching 63.79% across all years combined) — consistent with guideline-directed dual beta-blockade for HFrEF.

SGLT2 Emergence in 2024

Dapagliflozin and Jardiance appear as high-support MBA pairs (28–29%) starting in 2024, tracking the ~2-year lag between SGLT2 inhibitors' expanded FDA heart-failure indication and adoption in prescribing practice.

TruncatedSVD Beat PCA and t-SNE

TruncatedSVD captures 80% of variance in 3 components versus PCA's ~37% average and t-SNE's inconsistent 47–62% swing — the deciding factor in choosing it for the k=11 KMeans clustering.

Gender Signal Without Demographics

Random Forest and SVM classify patient gender from prescribing patterns alone — no demographic fields — with Prescriber as the single strongest differentiator, the root split in every decision tree.

XGBoost Wins on Every Task

96% cluster accuracy, 94.3% drug accuracy, and the best forecasting test R² (0.93 original data, 0.97 augmented) — XGBoost was the strongest model across all three problem types in this project.

Caught Our Own Data Leakage

A baseline linear model returning a perfect R² = 1.0000 was flagged as a methodology bug, not a result — a deliberate reminder that a suspiciously perfect score is a signal to investigate, not celebrate.