DSA LABData Science Applications
Experiment 06 ยท CO1

Who Will
Buy Again?

A retail company wants to predict customer purchases from historical sales. Explore the data, predict a customer live, then compare five machine-learning models on accuracy, precision, recall and F1 โ€” and recommend the best one.

Course IT416
Outcome CO1
Task Classification
Models 5 compared

Project at a glance

LIVE MODELS
0
Models
0
Metrics
0
RFM features
0
Concept videos
01

Lab Manual

Problem
A retail company wants to improve customer-purchase prediction using historical sales data. Analyse the dataset, identify suitable machine-learning techniques to improve prediction accuracy, compare multiple models, and recommend the best approach.
Aim
To frame the business problem as a supervised classification task, engineer useful features, train several models, evaluate them with appropriate metrics, and justify a recommendation.
Objectives
  • Explore historical sales data and define the target (will the customer purchase next period?).
  • Engineer features โ€” e.g. RFM: Recency, Frequency, Monetary value.
  • Train multiple classifiers and tune them.
  • Compare with accuracy, precision, recall, F1 and choose the best for the business goal.
Software
Python 3.x ยท Jupyter / Colab ยท Pandas, scikit-learn, Matplotlib.
Dataset
Any historical retail transactions table (e.g. the UCI "Online Retail" dataset) โ€” customer, date, items, amount โ€” from which RFM features and a purchase label are derived.
Outcome
CO1 โ€” analysing a real problem, choosing suitable techniques, and recommending a solution.
02

From Sales Log to Recommendation

There's no single "run the model" step. Real projects follow a pipeline โ€” and most of the value is in framing and features, not the algorithm.

STEP 1
UnderstandWhat decision does the business need? Define "purchase" and the time window.
STEP 2
Explore (EDA)Inspect sales, spot trends, missing values and class balance.
STEP 3
Engineer featuresTurn raw transactions into RFM: Recency, Frequency, Monetary.
STEP 4
Train modelsFit several classifiers on a training split.
STEP 5
EvaluateCompare on accuracy, precision, recall, F1, ROC-AUC.
STEP 6
RecommendPick the model that best serves the business goal.
03

Will This Customer Buy?

A logistic-regression model trained on RFM features. Move the sliders to describe a customer; the dot moves through the cloud of past customers (green = bought again, red = didn't), the dashed line is the model's decision boundary, and the gauge shows the predicted probability.

RFM purchase predictordrag the sliders โ†“
Frequency โ€” past purchases8
Recency โ€” days since last buy40
Monetary โ€” total spent (โ‚น)800
โ€”
Try it: a frequent, recent, high-spending customer lands deep in the green zone (high probability). Push recency up (a customer who hasn't visited in months) and watch the probability collapse โ€” recency is the strongest churn signal in retail.
04

Compare the Models

The heart of the experiment: train several classifiers and compare. Pick a metric โ€” the bars re-sort and the leader gets the gold bar and a Recommended tag. Notice the winner can change with the metric.

Model leaderboardrepresentative results on the sample data
Rank by:
04a

What the Metrics Mean

Confusion matrix

Pred Buy
Pred No
Actual Buy
TP
FN
Actual No
FP
TN

Every prediction lands in one of four boxes. The two green boxes are correct; the two red boxes are the two kinds of mistake.

The four metrics

  • Accuracy โ€” (TP+TN)/all. Overall correctness. Misleading when classes are imbalanced.
  • Precision โ€” TP/(TP+FP). Of those predicted to buy, how many actually did. Matters when false alarms are costly.
  • Recall โ€” TP/(TP+FN). Of the real buyers, how many we caught. Matters when missing a buyer is costly.
  • F1 โ€” harmonic mean of precision & recall. One balanced number when you care about both.
Business lens: for a marketing campaign with a tight budget you may favour precision (don't waste offers on non-buyers); to retain every possible customer you may favour recall (don't miss anyone about to churn). The "best" model depends on the goal โ€” which is exactly why CO1 asks you to recommend, not just compute.
05

Watch the Concepts

Two clear explainers from StatQuest with Josh Starmer on how we judge and compare classification models.

StatQuestThe Confusion MatrixHow TP/FP/TN/FN lead to accuracy, precision and recall โ€” the basis of model comparison.
StatQuestROC and AUC, Clearly ExplainedA single curve to compare classifiers across all thresholds.

Videos are embedded from YouTube and belong to their creators. If a frame is blank, your network may block YouTube โ€” search the titles on youtube.com.

06

The Program

Build RFM features, then loop over several models and compare them with a single, clean evaluation.

1 โ€” features_rfm.py
import pandas as pd

tx = pd.read_csv("online_retail.csv", parse_dates=["InvoiceDate"])
ref = tx["InvoiceDate"].max()

# Build RFM features per customer
rfm = tx.groupby("CustomerID").agg(
    Recency   = ("InvoiceDate", lambda d: (ref - d.max()).days),
    Frequency = ("InvoiceNo",   "nunique"),
    Monetary  = ("Amount",      "sum"),
).reset_index()

# Target: did the customer buy in the next period? (1/0)
rfm["WillBuy"] = (rfm["Recency"] < 60).astype(int)   # example label
2 โ€” compare_models.py
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

X = rfm[["Recency","Frequency","Monetary"]]; y = rfm["WillBuy"]
X = StandardScaler().fit_transform(X)
X_tr,X_te,y_tr,y_te = train_test_split(X,y,test_size=0.25,random_state=1)

models = {
  "Logistic Regression": LogisticRegression(),
  "KNN":                 KNeighborsClassifier(),
  "Naive Bayes":         GaussianNB(),
  "Decision Tree":       DecisionTreeClassifier(max_depth=5),
  "Random Forest":       RandomForestClassifier(n_estimators=200),
}
for name, m in models.items():
    m.fit(X_tr, y_tr); p = m.predict(X_te)
    print(f"{name:20s}",
          "acc", round(accuracy_score(y_te,p),3),
          "prec", round(precision_score(y_te,p),3),
          "rec", round(recall_score(y_te,p),3),
          "f1", round(f1_score(y_te,p),3))
3 โ€” recommend.py
# Robust comparison with cross-validation, then recommend
for name, m in models.items():
    scores = cross_val_score(m, X, y, cv=5, scoring="f1")
    print(name, "mean F1:", scores.mean().round(3))

# Recommendation: choose the model with the best F1 that meets
# the business need (precision for budgeted campaigns,
# recall for retention). Random Forest is a strong default.
07

Procedure & Result

Steps followed

1 ยท Frame
Define the prediction target from sales history.
2 ยท EDA
Explore distributions, missing data, class balance.
3 ยท Features
Engineer RFM and scale them.
4 ยท Train
Fit Logistic, KNN, Naive Bayes, Tree, Random Forest.
5 ยท Evaluate
Accuracy, precision, recall, F1 + cross-validation.
6 ยท Recommend
Pick the best model for the business goal.

Result

Historical sales were transformed into RFM features and used to train five classifiers. The models were compared on accuracy, precision, recall and F1. The ensemble (Random Forest) gave the best overall balance and is recommended, while the choice can shift toward precision- or recall-focused models depending on the campaign goal โ€” demonstrating CO1.

Conclusion: Better prediction comes mostly from good features (RFM) and honest evaluation, not just a fancier algorithm. Comparing several models on the right metric โ€” and tying that metric to the business decision โ€” is how you responsibly recommend an approach.
08

Viva Questions

What type of machine-learning problem is this?
Supervised binary classification โ€” predicting a yes/no label (will the customer purchase) from labelled historical data. If we predicted the amount spent instead, it would be regression.
What are RFM features and why are they useful here?
Recency (days since last purchase), Frequency (number of purchases) and Monetary (total spend). They compactly summarise customer behaviour and are strong predictors of future purchasing.
Why compare multiple models instead of using one?
No algorithm is best for every dataset (the "no free lunch" idea). Comparing several on the same data and metric shows which actually generalises best for this problem.
Difference between precision and recall?
Precision = of those predicted positive, how many were correct (TP/(TP+FP)). Recall = of all actual positives, how many were found (TP/(TP+FN)). There is usually a trade-off between them.
Why can accuracy be misleading?
With imbalanced classes (e.g. 95% non-buyers), a model that always predicts "no" scores 95% accuracy yet finds no buyers. Precision, recall, F1 or ROC-AUC give a truer picture.
What is cross-validation and why use it?
It splits the data into k folds, training on kโˆ’1 and testing on the held-out fold, rotating through all folds. It gives a more reliable, less luck-dependent estimate of performance.
Why does Random Forest often outperform a single decision tree?
It averages many de-correlated trees trained on bootstrapped samples and random feature subsets, reducing variance and overfitting while keeping low bias.
How would you handle class imbalance?
Resampling (oversample minority / undersample majority, e.g. SMOTE), class weights, threshold tuning, and evaluating with precision/recall/F1 or ROC-AUC rather than accuracy.