Views
No views yet
VotingClassifier that combines the strengths of four finely-tuned gradient boosting models: CatBoost, XGBoost, LightGBM, and Gradient Boosting. It was trained on a digital marketing dataset to identify customers with a high likelihood of making a purchase.joblib and can be loaded for inference as shown below.EngagementScore.1import joblib
2import pandas as pd
3import numpy as np
4
5# --- 1. Load the Trained Model ---
6# This assumes 'final_submission_model.pkl' is in the same directory.
7try:
8 model = joblib.load("conversion_prediction_model.pkl")
9 print("✅ Model loaded successfully.")
10except FileNotFoundError:
11 print("❌ Error: Ensure 'final_submission_model.pkl' is in the same directory as this script.")
12 exit()
13
14# --- 2. Define the Columns the Model was Trained On ---
15# This list MUST BE EXACTLY the same as the columns from your training data (X_train.columns)
16# It includes the original, engineered, and one-hot encoded columns in the correct order.
17TRAINING_COLUMNS = [
18 'Age', 'Income', 'WebsiteVisits', 'TimeOnSite', 'PagesPerVisit', 'AdSpend',
19 'EmailSubscriptions', 'SocialMediaEngagement', 'PreviousPurchases',
20 'LoyaltyPoints', 'EngagementScore', 'CostPerVisit', 'Gender_Female',
21 'Gender_Male', 'DeviceType_Desktop', 'DeviceType_Mobile',
22 'TrafficSource_Organic', 'TrafficSource_Paid', 'TrafficSource_Referral',
23 'AgeGroup_Adult', 'AgeGroup_Senior', 'AgeGroup_Young',
24 'IncomeTier_High', 'IncomeTier_Low', 'IncomeTier_Medium', 'IncomeTier_Very High'
25]
26
27
28def preprocess_for_prediction(raw_data_dict):
29 """
30 Takes a dictionary of raw data and preprocesses it for the model.
31 """
32 # Convert dictionary to a DataFrame
33 df = pd.DataFrame([raw_data_dict])
34
35 # --- Step A: Feature Engineering ---
36 # Create 'EngagementScore'
37 df['EngagementScore'] = df['TimeOnSite'] * df['PagesPerVisit']
38
39 # Create 'CostPerVisit' and handle potential division by zero
40 df['CostPerVisit'] = (df['AdSpend'] / df['WebsiteVisits']).replace([np.inf, -np.inf], 0).fillna(0)
41
42 # --- Step B: Binning for Age and Income ---
43 # AgeGroup Bins
44 age_bins = [0, 25, 45, 60, np.inf]
45 age_labels = ['Young', 'Adult', 'Senior', 'Very Senior'] # Adjusted to match potential notebook logic
46 df['AgeGroup'] = pd.cut(df['Age'], bins=age_bins, labels=age_labels, right=False)
47
48 # IncomeTier Bins (using quartiles as an example)
49 income_bins = [0, 45000, 85000, 120000, np.inf]
50 income_labels = ['Low', 'Medium', 'High', 'Very High']
51 df['IncomeTier'] = pd.cut(df['Income'], bins=income_bins, labels=income_labels, right=False)
52
53 # --- Step C: One-Hot Encoding ---
54 # Use pd.get_dummies for categorical columns
55 df = pd.get_dummies(df, columns=['Gender', 'DeviceType', 'TrafficSource', 'AgeGroup', 'IncomeTier'])
56
57 # --- Step D: Align Columns with Training Data ---
58 # Get all columns from the processed DataFrame
59 current_columns = df.columns
60
61 # Align the new data's columns with the original training columns
62 # This adds any missing one-hot encoded columns (and fills with 0)
63 # and ensures the final order is identical to the one the model was trained on.
64 aligned_df = df.reindex(columns=TRAINING_COLUMNS, fill_value=0)
65
66 return aligned_df
67
68
69# --- 3. Create Sample Raw Data Point ---
70# This dictionary represents a single new customer in its original format.
71new_customer_data = {
72 'Age': 38,
73 'Gender': 'Male',
74 'Income': 78000.0,
75 'WebsiteVisits': 15,
76 'TimeOnSite': 18.2,
77 'PagesPerVisit': 4.5,
78 'AdSpend': 150.0,
79 'EmailSubscriptions': 1,
80 'SocialMediaEngagement': 450,
81 'PreviousPurchases': 2,
82 'LoyaltyPoints': 1250,
83 'DeviceType': 'Desktop',
84 'TrafficSource': 'Organic'
85}
86
87
88# --- 4. Preprocess the Data and Make Prediction ---
89# Pass the raw data through the complete preprocessing pipeline
90processed_input = preprocess_for_prediction(new_customer_data)
91
92# Make the prediction using the fully preprocessed data
93prediction = model.predict(processed_input)
94prediction_proba = model.predict_proba(processed_input)
95
96
97# --- 5. Display the Result ---
98print("\n--- Prediction Results ---")
99print(f"Input Data: {new_customer_data}")
100
101if prediction[0] == 1:
102 print("\n🔮 Prediction: Customer WILL CONVERT")
103else:
104 print("\n🔮 Prediction: Customer WILL NOT CONVERT")
105
106print(f"Confidence Score (Probability of Conversion): {prediction_proba[0][1]:.2%}")
107EngagementScore, CostPerVisit) and binned numerical features (Age, Income) to capture non-linear patterns. Categorical features were one-hot encoded.VotingClassifier.| Metric | Score |
|---|---|
| Accuracy | 92.21% |
| F1-Score (Conversion) | 0.9569 |
| Precision (Conversion) | 0.9326 |
| Recall (Conversion) | 0.9821 |