-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
121 lines (103 loc) · 5.3 KB
/
Copy pathapp.py
File metadata and controls
121 lines (103 loc) · 5.3 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import os
import matplotlib.pyplot as plt
import seaborn as sns
st.set_page_config(page_title="Enterprise Customer Insights Hub", layout="wide", page_icon="📊")
# Load model, scaler, and source data with performance caching
@st.cache_resource
def load_production_assets():
model = joblib.load('models/kmeans_model.pkl')
scaler = joblib.load('models/scaler.pkl')
raw_df= pd.read_csv('data/Mall_Customers.csv')
return model, scaler, raw_df
# Fail-safe check for missing trained model files
try:
model, scaler, raw_df = load_production_assets()
X_scaled = scaler.transform(raw_df.iloc[:, [3, 4]].values)
raw_df['Cluster'] = model.predict(X_scaled)
except Exception as e:
st.error(" System Error: Please execute 'customer_clustering.py' in the terminal to train and dump the model objects first!")
st.stop()
# Dashboard Main Header
st.title(" Enterprise Customer Analytics & Segmentation Hub")
st.markdown("Welcome to the AI-powered marketing strategy dashboard. Analyze overall customer base dynamics or predict new instances.")
# Setup tabs for modular navigation
tab1, tab2, tab3 = st.tabs([" Real-time Inference", " Customer Base Analytics", "📋 Raw Dataset Viewer"])
# --- TAB 1: Real-time User Prediction ---
with tab1:
st.subheader("Predict Customer Segment")
col1, col2 = st.columns(2)
with col1:
income = st.number_input("Annual Income (in $k):", min_value=15, max_value=150, value=50, step=1)
spending_score = st.slider("Spending Score Indicator (1-100):", min_value=1, max_value=100, value=50)
with col2:
st.write(" ")
st.write(" ")
if st.button("Process Analytics Pipeline", use_container_width=True):
user_payload = np.array([[income, spending_score]])
user_payload_scaled = scaler.transform(user_payload)
predicted_cluster = model.predict(user_payload_scaled)[0]
# Map marketing business strategies to assigned clusters
cluster_strategies = {
0: ("Standard Core Customers", "Balanced income and spending pattern. Targeted with contextual newsletter updates and milestone discounts."),
1: ("High-Value Whales (VIP)", "High spending, high income. Primary revenue catalyst. Retain with exclusive rewards, white-glove support, and early product previews."),
2: ("Conservative Affluents", "High financial capacity, low consumption behavior. Engage using personalized premium offerings, high-quality bundles, and value justification campaigns."),
3: ("High-Velocity Spenders", "Socio-economically lower-income bracket but extraordinarily reactive to trends. Target via flash sales, deferred payment options (BNPL), and urgency marketing."),
4: ("Low-Priority Tier", "Minimal income and low engagement score. Low operational overhead allocation recommended. Standard automated drip campaigns only.")
}
segment_name, business_strategy = cluster_strategies.get(predicted_cluster, ("Standard", ""))
st.success(f" Execution Success! Segment Assigned: **{segment_name}** (Cluster Index {predicted_cluster})")
st.warning(f" **Operational Marketing Strategy:** {business_strategy}")
# --- TAB 2: Dynamic Visual Analytics ---
with tab2:
st.subheader("Data Visualization & Model Performance Metrics")
metric_col1, metric_col2, metric_col3 = st.columns(3)
metric_col1.metric("Total Sample Size", f"{len(raw_df)} Customers")
metric_col2.metric("Configured Clusters (K)", "5 Segments")
metric_col3.metric("Clustering Engine", "Scikit-Learn KMeans")
st.markdown("---")
viz_col1, viz_col2 = st.columns(2)
with viz_col1:
st.markdown("### Model Segment Mapping")
fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(
data=raw_df,
x='Annual Income (k$)',
y='Spending Score (1-100)',
hue='Cluster',
palette='tab10',
s=100,
style='Cluster',
ax=ax
)
plt.title('Customer Segments Distribution')
st.pyplot(fig)
with viz_col2:
st.markdown("### Mathematical Verification (Elbow Curve)")
wcss = []
for i in range(1, 11):
from sklearn.cluster import KMeans
kmeans_check = KMeans(n_clusters=i, init='k-means++', random_state=42)
kmeans_check.fit(X_scaled)
wcss.append(kmeans_check.inertia_)
fig, ax = plt.subplots(figsize=(8, 4))
plt.plot(range(1, 11), wcss, marker='o', linestyle='--', color='b')
plt.title('The Elbow Point Graph (Model Evaluation)')
plt.xlabel('Number of Clusters')
plt.ylabel('WCSS')
st.pyplot(fig)
# --- TAB 3: Data Table Index ---
with tab3:
st.subheader("Segmented Database Index")
st.dataframe(raw_df, use_container_width=True)
st.markdown("### Segment Averages Table")
summary_table = raw_df.groupby('Cluster').agg({
'Age': 'mean',
'Annual Income (k$)': 'mean',
'Spending Score (1-100)': 'mean',
'CustomerID': 'count'
}).rename(columns={'CustomerID': 'Total Population Count'})
st.table(summary_table)