Dataset Documentation

Online Shoppers
Intention Dataset

A complete reference for every input field, feature contribution, preprocessing pipeline, and model performance behind the ShopperAI purchase prediction system.

12,330 Sessions
17 Input Features
Binary Classification
Kaggle Source
View on Kaggle Open Dashboard
Dataset At a Glance
Total Sessions
12,199
After removing 131 duplicate rows
Class Distribution
Not Purchased 84.5%
Purchased 15.5%
Best Model
Hist. Gradient Boosting
PR-AUC 0.7585 · ROC-AUC 0.9327
Prediction Threshold
0.49
Optimized via F1-score tuning
Contents Overview Input Features Engineered Pipeline Models Performance Threshold API Usage

What is this dataset?

The Online Shoppers Intention dataset was collected from an e-commerce platform over one year. Each row represents a single browsing session, and the goal is to predict whether that session will end in a purchase.

Source
Kaggle / UCI ML Repo
by Henry Sue
Task Type
Binary Classification
Predict Revenue (0 or 1)
Imbalance
84.5% vs 15.5%
Handled via balanced weights
⚠️

Class Imbalance Note

Only ~15.5% of sessions result in a purchase. This imbalance was addressed using class_weight="balanced" in tree-based models and optimizing for PR-AUC (Precision-Recall Area Under Curve) instead of accuracy, which is a more informative metric for imbalanced datasets.

All 17 Input Fields

These are the raw features available from the dataset that are sent directly to the prediction API. Impact levels reflect observed influence on the Revenue target.

Numerical Features (10)

Field Name Type Description Range Impact
PageValues float Average value of pages viewed before completing an e-commerce transaction. Pages contributing to a purchase are weighted by their transactional value. 0 – 361.76
High
ProductRelated int Number of product-related pages visited during the session. High counts indicate active product exploration. 0 – 705
High
ProductRelated_Duration float Total time (seconds) spent on product-related pages. Longer time suggests deeper product consideration. 0 – 63,974 s
High
BounceRates float Percentage of visitors who enter and immediately exit the site from that page, without any further interaction. Lower values indicate more engaged visitors. 0.0 – 0.20
Medium
ExitRates float For each page, the percentage of all sessions that ended on that page. Different from bounce rate — applies even if the user visited other pages first. 0.0 – 0.20
Medium
Administrative int Number of administrative pages visited (e.g. account management, order history, settings pages). 0 – 27
Low
Administrative_Duration float Total time (seconds) spent on administrative pages during the session. 0 – 3,399 s
Low
Informational int Number of informational pages visited (e.g. about us, contact, FAQ, shipping info). 0 – 24
Low
Informational_Duration float Total time (seconds) spent on informational pages during the session. 0 – 2,549 s
Low
SpecialDay float Indicates how close the session date is to a special shopping day (e.g. Mother's Day, Valentine's). 0.0 = not close, 1.0 = very close. 0.0 – 1.0
Low

Categorical Features (7)

Field Name Type Description Values Impact
VisitorType string Whether the visitor is returning to the site or visiting for the first time. Returning visitors tend to have higher purchase intent. Returning_Visitor
New_Visitor
Other
Medium
Month string Month of the year the session occurred. Seasonality plays a role — November and December show higher purchase rates due to holidays. Feb, Mar, May, June,
Jul, Aug, Sep, Oct,
Nov, Dec
Medium
TrafficType int code Integer code representing how the visitor arrived at the site (e.g. direct, referral, paid search, social media). Different traffic sources have different conversion rates. 1 – 20
Medium
Region int code Geographic region of the visitor (anonymized integer code). Regional purchasing patterns may vary significantly. 1 – 9
Low
OperatingSystems int code Operating system used by the visitor (anonymized integer code). Device type inferred from OS may weakly correlate with purchase behavior. 1 – 8
Low
Browser int code Browser used by the visitor (anonymized integer code). Has minimal direct predictive power but contributes marginally to the model. 1 – 13
Low
Weekend boolean Whether the session occurred on a weekend. Weekday vs weekend browsing patterns differ slightly in conversion likelihood. true / false
Low
ℹ️

About PageValues

PageValues is technically a data leakage candidate — it's computed using transactional data that only exists after a purchase. In real-time prediction, this value may be 0 for all sessions (since no transaction has occurred yet). For demo purposes the API accepts it, and non-zero values will strongly push the prediction toward "Will Purchase".

Engineered Features

These features were derived from the raw inputs to capture richer behavioral signals. They are computed automatically inside the model pipeline — you do not need to provide them as inputs.

TotalDuration
= Admin_Duration + Info_Duration + Product_Duration
Total time the visitor spent on the website during the session. Users spending more total time generally show higher purchase engagement.
TotalPages
= Administrative + Informational + ProductRelated
Total number of pages visited. Users who explore many pages are likely in an active decision-making or comparison phase.
ProductDurationPerPage
= ProductRelated_Duration / ProductRelated
Average time per product page. Deep dwell time per product page is a strong signal of genuine purchase consideration.
ProductEngagement
= ProductRelated × ProductRelated_Duration
Combined engagement score measuring breadth (pages visited) × depth (time spent). A high score is the strongest composite purchase signal.
ExitBounceGap
= ExitRates − BounceRates
Measures how much exit behavior exceeds single-page bounce behavior. A positive gap indicates users are leaving after exploring, not just bouncing immediately.
DurationWeightedExit
= TotalDuration × ExitRates
Combines session length with exit tendency. Long sessions with high exit rates may indicate research without intent to buy.
ProductPageRatio
= ProductRelated / TotalPages
Proportion of the session focused on product pages. Higher ratios indicate a product-browsing session rather than an informational one.
Log-transformed Durations
= log1p(duration_feature)
Duration features are highly right-skewed with extreme outliers. Log1p transformation compresses the scale and stabilizes model training.

How Raw Data Becomes a Prediction

The model uses a sklearn Pipeline that automatically handles imputation, encoding, and scaling before feeding data to the classifier.

1

Feature Engineering

TotalDuration, TotalPages, ratios, engagement scores, and log-transformed duration features are derived from the raw 17 inputs. This step adds 20+ additional features that help the model capture non-linear behavioral patterns.

+20 derived featureslog1p transformratio engineering
2

Missing Value Imputation

Numerical columns use median imputation (robust to outliers). Categorical columns use most-frequent imputation. The dataset had a small percentage of missing values in numeric features only.

SimpleImputer(strategy="median")SimpleImputer(strategy="most_frequent")
3

Numerical Scaling

RobustScaler is used instead of StandardScaler because duration and page-count features contain significant outliers. RobustScaler centers using the median and scales using the IQR, making it resistant to extreme values.

RobustScalerOutlier-resistantIQR-based scaling
4

Categorical Encoding

OneHotEncoder with min_frequency=10 is applied to Month, VisitorType, Weekend, and the integer-code columns (OperatingSystems, Browser, Region, TrafficType). Rare categories are grouped as "infrequent."

OneHotEncoderhandle_unknown="ignore"min_frequency=10
5

ColumnTransformer

A ColumnTransformer applies the numeric and categorical pipelines in parallel and combines the results into a single feature matrix before passing to the classifier.

ColumnTransformerParallel processing
6

Classification

The preprocessed features are fed into the best-performing classifier. All steps — including feature engineering — are serialized into a single .pkl file so the API only needs raw inputs.

HistGradientBoostingClassifierjoblib serializedpredict_proba

Six Models Trained & Compared

All models were evaluated using 5-fold Stratified Cross-Validation with PR-AUC as the scoring metric, followed by hyperparameter tuning via RandomizedSearchCV.

★ Best Model
Hist Gradient Boosting
0.7585
CV PR-AUC
Soft Voting Ensemble
0.7561
CV PR-AUC
Gradient Boosting
0.7541
CV PR-AUC
Random Forest
0.7538
CV PR-AUC
Extra Trees
0.7391
CV PR-AUC
Logistic Regression
0.6644
CV PR-AUC
💡

Why PR-AUC over Accuracy?

With 84.5% of sessions being non-purchases, a naive model predicting "no purchase" every time would achieve 84.5% accuracy — but be completely useless. PR-AUC measures performance specifically on the minority (purchase) class, penalizing models that simply predict the majority class and rewarding those that correctly identify true buyers.

Test Set Results — Hist Gradient Boosting

Performance on the held-out test set (20% of data, ~2,445 sessions), never seen during training or hyperparameter tuning.

90.5%
Accuracy
0.9327
ROC-AUC
0.7415
PR-AUC
0.0707
Brier Score ↓

Confusion Matrix (Threshold = 0.49)

1,969
True Negative
94
False Positive
139
False Negative
243
True Positive

Purchase Class Metrics

Precision72%
Recall64%
F1-Score68%
Support382 sessions

Threshold & Decision Boundary

The model outputs a probability score between 0 and 1. A decision threshold converts this into a binary prediction.

Decision Boundary at 0.49

0.49 threshold
0.0 — Will Not Purchase 1.0 — Will Purchase
Probability ≥ 0.49
Will Purchase
Strong enough evidence of purchase intent detected in the browsing session.
Probability < 0.49
Will Not Purchase
Insufficient purchase signals — visitor may need re-engagement or retargeting.
🎯

Why 0.49 instead of the default 0.50?

The threshold was tuned by sweeping values from 0.05 to 0.90 and selecting the threshold that maximizes the F1-score on the purchase class. At 0.49 the model achieves the best balance between Precision (72%) and Recall (64%), slightly favoring capturing more true buyers at the cost of a few extra false alarms.

Calling the Prediction API

Send a POST request with a JSON body containing all 17 input fields. The API returns a probability score, label, and threshold.

POST /predict
fetch('https://xstynwx-online-shoppers-api.hf.space/predict', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    "Administrative": 2,
    "Administrative_Duration": 0,
    "Informational": 0,
    "Informational_Duration": 0,
    "ProductRelated": 15,
    "ProductRelated_Duration": 1020.5,
    "BounceRates": 0.3,
    "ExitRates": 0.05,
    "PageValues": 125.3,
    "SpecialDay": 0,
    "Month": "Nov",
    "OperatingSystems": 2,
    "Browser": 4,
    "Region": 1,
    "TrafficType": 2,
    "VisitorType": "Returning_Visitor",
    "Weekend": true
  })
})
// Response:
{
  "will_purchase": true,
  "prediction": 1,
  "prediction_label": "Will Purchase",
  "probability": 0.8134,
  "threshold": 0.49
}
✅

Health Check

GET https://xstynwx-online-shoppers-api.hf.space/health — returns 200 OK with a status message when the API is running.

📚

Interactive Docs

FastAPI auto-generates Swagger UI at /docs. Test the API directly from your browser without writing any code.