End-to-End E-Commerce Purchase Intent Prediction Pipeline
Machine LearningModel answerLast updated
Design a robust data cleaning, pipeline, validation, and threshold-tuning strategy to predict session conversions evaluated on weighted F1 score.
You are tasked with creating an end-to-end machine learning pipeline to forecast whether a web browsing session ends in a commercial transaction (outcome). The dataset consists of numerical metrics (e.g., duration, page views, drop-off rates) and categorical/encoded indicators (e.g., user operating system, traffic source type, region, promotional flag).
Your pipeline will be evaluated on unseen test data using weighted F1-score.
Core Constraints & Rules
- Column Filtering: Any feature containing more than 50% missing values or possessing zero variance (a single unique value) across the training dataset must be discarded.
- Strict Data Leakage Prevention: All stateful data transformations (imputation statistics, scaling factors, category encodings, column selection decisions) must be fitted exclusively on training splits or inside cross-validation folds.
- Format Integrity: The final output file
submissions.csvmust map every test setidto a binary integer predictionoutcome$\in {0, 1}$. No rows from the test set may be omitted.
Discuss your architectural decisions, data audit steps, leakage prevention strategies, metric optimization nuances, and provide a complete reference Python pipeline.
Hints
Hint 1
Identify domain-level bugs early: page counts cannot be negative, exit/bounce rates must lie within [0.0, 1.0], and sentinel values like -999 must be coerced to NaN before pipeline fitting.
Hint 2
Be cautious with imbalanced target metrics: standard minority-class F1 optimization differs from weighted F1. Aggressively pushing minority recall can harm overall weighted F1 by increasing false positives in the majority class.
Hint 3
Categorical integer fields like OS or browser codes represent nominal IDs, not ordinal numeric relationships. Treat them as categorical features and one-hot encode them.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Structural Framework & Solution Strategy
A production-grade competitive notebook or ML take-home requires a structured execution flow split into five distinct stages:
[ Data Audit & Cleaning ] ──> [ Pipeline & Preprocessing ] ──> [ Stratified CV ] ──> [ Threshold Tuning ] ──> [ Inference ]
Key Architectural Decisions
1. Stateless vs. Stateful Preprocessing
To strictly prevent data leakage:
- Stateless Transformations (rule-based domain assertions, string stripping, null coercion, sentinel removal) run deterministically across both training and test sets prior to splitting.
- Stateful Transformations (column filtering by missingness/variance, numerical imputation medians, standard scaling, one-hot category maps) are encapsulated inside
sklearn.pipeline.Pipelineor calculated strictly on training folds.
2. Domain-Specific Data Auditing
Raw web telemetry commonly suffers from tracking bugs:
- String Sentinels: Values such as
"?","null","NONE","-999", or trailing whitespaces must be unified to standardnp.nan. - Out-of-Bounds Metrics: Negative durations or page view counts are invalid (coerced to
NaN). - Bounded Statistics: Rates (e.g., bounce rate, exit rate) strictly bound to $[0, 1]$ must have values $< 0$ or $> 1$ invalidated.
- Categorical IDs: Operating systems, regions, and traffic channels recorded as numeric codes (e.g.,
OS=3) represent nominal variables without ordinal hierarchy. They must be encoded as categorical strings before one-hot encoding.
Understanding the Evaluation Metric: Weighted F1
The weighted F1 score computes the F1 metric for each class independently and averages them weighted by class support ($N_k$):
$$\text{Weighted F1} = \sum_{k \in {0, 1}} \left( \frac{N_k}{N_{total}} \right) \times \text{F1}_k$$
Critical Implication for Imbalanced Datasets
In session data, positive conversions typically form a minority class ($\approx 10\text{--}20%$).
- Optimizing for minority-class F1 ($\text{F1}_1$) often encourages over-predicting the positive class to maximize recall.
- Optimizing for weighted F1 penalizes false positives heavily because the majority class ($k=0$) carries $80\text{--}90%$ of the total metric weight.
- Consequently, techniques like aggressive oversampling (SMOTE) or high positive class weights (
class_weight='balanced') can degrade the final weighted F1 score by compromising majority class precision. - The optimal decision threshold $t^*$ for converting predicted probabilities into binary labels $\hat{y} = \mathbb{I}(P(y=1|X) \ge t)$ must be searched directly over pooled Out-Of-Fold (OOF) validation predictions to maximize weighted F1.
Validation Strategy & Complexity Analysis
- Validation Scheme: 5-Fold
StratifiedKFoldwith fixed random seeding. Stratification preserves the target ratio across all folds, ensuring each validation set reflects the population class distribution. - Time Complexity:
- Preprocessing & Encoding: $\mathcal{O}(N \cdot D)$
- Model Training (Gradient Boosting / HistGBDT): $\mathcal{O}(K \cdot T \cdot N \cdot D_{encoded})$, where $K$ is folds, $T$ is trees.
- Threshold Tuning: Grid search over $100$ probability cutoffs on $N$ predictions takes $\mathcal{O}(100 \cdot N)$ (negligible).
- Space Complexity: $\mathcal{O}(N \cdot D_{encoded})$ for sparse/dense pipeline outputs.
Complete Python Solution
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
TARGET = "outcome"
ID_COL = "id"
NULL_REPRESENTATIONS = {"", "?", "nan", "none", "null", "n/a", "na", "-", "-999"}
BOOLEAN_MAPPING = {"true": 1, "false": 0, "yes": 1, "no": 0}
NOMINAL_KEYWORDS = ("device", "traffic", "browser", "region", "os", "type", "channel")
def audit_and_clean_stateless(df: pd.DataFrame) -> pd.DataFrame:
"""Applies purely stateless cleaning rules to data.
Safe to apply to train and test independently without data leakage.
"""
df = df.copy()
df.columns = df.columns.str.strip()
for col in df.columns:
if col == ID_COL:
continue
# Standardize strings, handle sentinels & booleans
if df[col].dtype == object:
cleaned_str = df[col].astype(str).str.strip().str.lower()
cleaned_str = cleaned_str.where(~cleaned_str.isin(NULL_REPRESENTATIONS), np.nan)
cleaned_str = cleaned_str.replace(BOOLEAN_MAPPING)
# Attempt numeric conversion if valid parsing ratio is high
converted_num = pd.to_numeric(cleaned_str, errors="coerce")
if converted_num.notna().sum() >= 0.85 * cleaned_str.notna().sum():
df[col] = converted_num
else:
df[col] = cleaned_str
# Domain boundary validation for numerical columns
col_lower = col.lower()
if pd.api.types.is_numeric_dtype(df[col]):
# Coerce extreme sentinel numbers
df.loc[df[col] <= -999, col] = np.nan
# Non-negativity constraints for counts and durations
if any(term in col_lower for term in ("count", "page", "time", "duration", "view")):
df.loc[df[col] < 0, col] = np.nan
# Bounded rates constraints [0, 1]
if any(term in col_lower for term in ("rate", "pct", "percent", "score", "ratio")):
df.loc[(df[col] < 0.0) | (df[col] > 1.0), col] = np.nan
return df
def execute_pipeline():
# 1. Load Raw Data
raw_train = pd.read_csv("train.csv")
raw_test = pd.read_csv("test.csv")
# 2. Stateless Cleaning
clean_train = audit_and_clean_stateless(raw_train)
clean_test = audit_and_clean_stateless(raw_test)
# 3. Target Processing
clean_train = clean_train[clean_train[TARGET].notna()].copy()
clean_train[TARGET] = clean_train[TARGET].astype(float).round().astype(int)
# 4. Feature Selection based strictly on Training set criteria
initial_features = [c for c in clean_train.columns if c not in (ID_COL, TARGET)]
dropped_cols = []
for col in initial_features:
missing_pct = clean_train[col].isna().mean()
unique_vals = clean_train[col].nunique(dropna=True)
if missing_pct > 0.50 or unique_vals <= 1:
dropped_cols.append(col)
selected_features = [c for c in initial_features if c not in dropped_cols]
print(f"Dropped {len(dropped_cols)} columns based on training rules: {dropped_cols}")
# 5. Type Assignment (Nominal Categorical vs. Continuous Numerical)
categorical_cols = [
c for c in selected_features
if clean_train[c].dtype == object or any(kw in c.lower() for kw in NOMINAL_KEYWORDS)
]
numerical_cols = [c for c in selected_features if c not in categorical_cols]
for c in categorical_cols:
clean_train[c] = clean_train[c].astype(str)
clean_test[c] = clean_test[c].astype(str)
X_train = clean_train[selected_features]
y_train = clean_train[TARGET]
X_test = clean_test[selected_features]
# 6. Build Preprocessor Construction Helper
def build_preprocessor(scale_numeric: bool = False) -> ColumnTransformer:
num_transformers = [("imputer", SimpleImputer(strategy="median"))]
if scale_numeric:
num_transformers.append(("scaler", StandardScaler()))
return ColumnTransformer(
transformers=[
("num", Pipeline(num_transformers), numerical_cols),
(
"cat",
OneHotEncoder(handle_unknown="ignore", min_frequency=15, sparse_output=False),
categorical_cols,
),
]
)
# 7. Candidate Models Setup
pipelines = {
"LogisticRegression": Pipeline([
("preprocessor", build_preprocessor(scale_numeric=True)),
("classifier", LogisticRegression(max_iter=1000, C=1.0, random_state=42))
]),
"HistGradientBoosting": Pipeline([
("preprocessor", build_preprocessor(scale_numeric=False)),
("classifier", HistGradientBoostingClassifier(
max_iter=300,
learning_rate=0.05,
early_stopping=True,
random_state=42
))
]),
}
# 8. Cross-Validation and Out-of-Fold Threshold Tuning
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
best_overall_score = -1.0
best_model_name = None
best_threshold = 0.5
best_pipeline = None
for name, pipeline in pipelines.items():
# Get Out-Of-Fold predicted probabilities
oof_probs = cross_val_predict(
pipeline, X_train, y_train, cv=cv, method="predict_proba"
)[:, 1]
# Search for threshold maximizing Weighted F1
thresholds = np.linspace(0.1, 0.9, 81)
scores = [
f1_score(y_train, (oof_probs >= t).astype(int), average="weighted")
for t in thresholds
]
idx_max = np.argmax(scores)
opt_thresh = thresholds[idx_max]
opt_score = scores[idx_max]
print(f"Model: {name} | Best OOF Weighted F1: {opt_score:.4f} at Threshold: {opt_thresh:.2f}")
if opt_score > best_overall_score:
best_overall_score = opt_score
best_model_name = name
best_threshold = opt_thresh
best_pipeline = pipeline
# 9. Retrain Winning Pipeline on Full Training Set & Generate Predictions
print(f"\nFitting selected model '{best_model_name}' on complete training data...")
best_pipeline.fit(X_train, y_train)
test_probs = best_pipeline.predict_proba(X_test)[:, 1]
final_predictions = (test_probs >= best_threshold).astype(int)
# 10. Generate Final Submission File
submission = pd.DataFrame({
ID_COL: raw_test[ID_COL],
TARGET: final_predictions
})
submission.to_csv("submissions.csv", index=False)
print(f"Successfully exported submissions.csv with {len(submission)} rows.")
if __name__ == "__main__":
execute_pipeline()