-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
95 lines (82 loc) · 3.35 KB
/
Copy pathapp.py
File metadata and controls
95 lines (82 loc) · 3.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import streamlit as st
import joblib
import plotly.graph_objects as go
import numpy as np
import pandas as pd
# Load model, scaler, and features
model = joblib.load("purchase_model.pkl")
scaler = joblib.load("scaler.pkl")
feature_names = joblib.load("feature_names.pkl")
st.title("🛒 Consumer Purchase Propensity Prediction")
st.write("Predict whether a customer is likely to make a purchase based on their online behavior.")
# Input fields
st.subheader("📋 Enter Customer Details:")
time_on_site = st.number_input("Time on Site (seconds)", min_value=0)
pages_viewed = st.number_input("Pages Viewed", min_value=0)
cart_additions = st.number_input("Cart Additions", min_value=0)
ad_clicked = st.selectbox("Ad Clicked", [False, True])
discount_viewed = st.selectbox("Discount Viewed", [False, True])
previous_purchases = st.number_input("Previous Purchases", min_value=0)
session_duration = st.number_input("Session Duration (seconds)", min_value=0)
gender = st.selectbox("Gender", ["Male", "Female"])
region = st.selectbox("Region", ["North", "South", "East", "West"])
device_type = st.selectbox("Device Type", ["Mobile", "Tablet", "Desktop"])
# Prepare input data (no manual encoding)
input_df = pd.DataFrame({
"Time_on_Site": [time_on_site],
"Pages_Viewed": [pages_viewed],
"Cart_Additions": [cart_additions],
"Ad_Clicked": [int(ad_clicked)],
"Discount_Viewed": [int(discount_viewed)],
"Previous_Purchases": [previous_purchases],
"Session_Duration": [session_duration],
"Gender": [gender],
"Region": [region],
"Device_Type": [device_type]
})
# Apply same encoding as training
input_df = pd.get_dummies(input_df, columns=["Gender", "Region", "Device_Type"], drop_first=True)
# Add missing columns if any
for col in feature_names:
if col not in input_df.columns:
input_df[col] = 0
# Reorder columns
input_df = input_df[feature_names]
# Scale numeric features
num_cols = ["Time_on_Site", "Pages_Viewed", "Cart_Additions", "Previous_Purchases", "Session_Duration"]
input_df[num_cols] = scaler.transform(input_df[num_cols])
# Predict
import plotly.graph_objects as go
# Predict
if st.button("🔍 Predict Purchase Propensity"):
prediction = model.predict(input_df)[0]
prob = model.predict_proba(input_df)[0][1]
prob_percent = prob * 100
# Text output
if prediction == 1:
st.success(f"✅ This customer is likely to make a purchase! (Confidence: {prob:.2f})")
else:
st.warning(f"❌ This customer is unlikely to make a purchase. (Confidence: {prob:.2f})")
# Thin-needle gauge
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=prob_percent,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': "🛒 Purchase Probability (%)", 'font': {'size': 24}},
number={'font': {'size': 28, 'color': 'darkblue'}},
gauge={
'axis': {'range': [0, 100]},
'bar': {'color': "rgba(0,0,0,0)"}, # hide thick bar
'steps': [
{'range': [0, 50], 'color': 'red'},
{'range': [50, 75], 'color': 'yellow'},
{'range': [75, 100], 'color': 'green'}
],
'threshold': {
'line': {'color': 'black', 'width': 6}, # thin needle
'thickness': 1.0,
'value': prob_percent
}
}
))
st.plotly_chart(fig, use_container_width=True)