final
Browse files- app.py +152 -0
- requirements.txt +6 -0
- shopping_trends.csv +0 -0
app.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
import seaborn as sns
|
6 |
+
from sklearn.cluster import KMeans
|
7 |
+
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder
|
8 |
+
from sklearn.pipeline import Pipeline
|
9 |
+
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score
|
10 |
+
|
11 |
+
st.title("Sales Trend Prediction using KMeans Clustering")
|
12 |
+
|
13 |
+
def load_data():
|
14 |
+
return pd.read_csv("shopping_trends.csv")
|
15 |
+
|
16 |
+
df = load_data()
|
17 |
+
|
18 |
+
# Select relevant features for clustering
|
19 |
+
features = ['Gender', 'Item Purchased', 'Previous Purchases', 'Frequency of Purchases', 'Purchase Amount (USD)']
|
20 |
+
df_filtered = df[features].copy()
|
21 |
+
|
22 |
+
# Convert Frequency of Purchases to string
|
23 |
+
df_filtered['Frequency of Purchases'] = df_filtered['Frequency of Purchases'].astype(str)
|
24 |
+
|
25 |
+
# One-hot encode categorical features
|
26 |
+
categorical_features = ['Gender', 'Item Purchased', 'Frequency of Purchases']
|
27 |
+
numerical_features = ['Previous Purchases', 'Purchase Amount (USD)']
|
28 |
+
|
29 |
+
ohe = OneHotEncoder(drop='first', sparse_output=False)
|
30 |
+
encoded_cats = ohe.fit_transform(df_filtered[categorical_features])
|
31 |
+
categorical_df = pd.DataFrame(encoded_cats, columns=ohe.get_feature_names_out(categorical_features), index=df.index)
|
32 |
+
|
33 |
+
df_processed = pd.concat([df_filtered[numerical_features], categorical_df], axis=1)
|
34 |
+
|
35 |
+
# Standardizing the data
|
36 |
+
scaler = StandardScaler()
|
37 |
+
X_scaled = scaler.fit_transform(df_processed)
|
38 |
+
|
39 |
+
# KMeans Clustering
|
40 |
+
n_clusters = 3 # Set the number of clusters
|
41 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
|
42 |
+
df['Cluster'] = kmeans.fit_predict(X_scaled)
|
43 |
+
|
44 |
+
# Compute Clustering Metrics
|
45 |
+
silhouette = silhouette_score(X_scaled, df['Cluster'])
|
46 |
+
davies_bouldin = davies_bouldin_score(X_scaled, df['Cluster'])
|
47 |
+
calinski_harabasz = calinski_harabasz_score(X_scaled, df['Cluster'])
|
48 |
+
|
49 |
+
def predict_cluster(user_input):
|
50 |
+
"""Predicts the cluster for a new user input."""
|
51 |
+
user_df = pd.DataFrame([user_input])
|
52 |
+
user_df['Frequency of Purchases'] = user_df['Frequency of Purchases'].astype(str)
|
53 |
+
user_cats = ohe.transform(user_df[categorical_features])
|
54 |
+
user_processed = pd.concat([user_df[numerical_features], pd.DataFrame(user_cats, columns=ohe.get_feature_names_out(categorical_features))], axis=1)
|
55 |
+
user_scaled = scaler.transform(user_processed)
|
56 |
+
return kmeans.predict(user_scaled)[0]
|
57 |
+
|
58 |
+
# Create Tabs
|
59 |
+
tab1, tab2, tab3 = st.tabs(["Dataset & Metrics", "Visualization", "Sales Trend Prediction"])
|
60 |
+
|
61 |
+
with tab1:
|
62 |
+
st.subheader("Dataset Preview")
|
63 |
+
st.write(df.head())
|
64 |
+
|
65 |
+
st.subheader("Clustering Metrics")
|
66 |
+
st.write(f"Number of Clusters: {n_clusters}")
|
67 |
+
st.write(f"Silhouette Score: {silhouette:.4f}")
|
68 |
+
st.write(f"Davies-Bouldin Score: {davies_bouldin:.4f}")
|
69 |
+
st.write(f"Calinski-Harabasz Score: {calinski_harabasz:.4f}")
|
70 |
+
|
71 |
+
with tab2:
|
72 |
+
st.subheader("Data Visualizations")
|
73 |
+
|
74 |
+
# Elbow Method Visualization
|
75 |
+
distortions = []
|
76 |
+
K_range = range(2, 11)
|
77 |
+
for k in K_range:
|
78 |
+
kmeans_tmp = KMeans(n_clusters=k, random_state=42)
|
79 |
+
kmeans_tmp.fit(X_scaled)
|
80 |
+
distortions.append(kmeans_tmp.inertia_)
|
81 |
+
|
82 |
+
fig, ax = plt.subplots()
|
83 |
+
ax.plot(K_range, distortions, marker='o')
|
84 |
+
ax.set_xlabel('Number of Clusters')
|
85 |
+
ax.set_ylabel('Distortion')
|
86 |
+
ax.set_title('Elbow Method for Optimal K')
|
87 |
+
st.pyplot(fig)
|
88 |
+
|
89 |
+
# Cluster Distribution Plot
|
90 |
+
fig, ax = plt.subplots()
|
91 |
+
sns.countplot(x=df['Cluster'], palette='viridis', ax=ax)
|
92 |
+
ax.set_xlabel('Cluster')
|
93 |
+
ax.set_ylabel('Count')
|
94 |
+
ax.set_title('Cluster Distribution')
|
95 |
+
st.pyplot(fig)
|
96 |
+
|
97 |
+
# Visualizations for Item Purchased distribution
|
98 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
99 |
+
sns.countplot(y=df['Item Purchased'], order=df['Item Purchased'].value_counts().index, palette='viridis', ax=ax)
|
100 |
+
ax.set_title("Overall Item Purchase Distribution")
|
101 |
+
ax.set_xlabel("Count")
|
102 |
+
ax.set_ylabel("Item Purchased")
|
103 |
+
st.pyplot(fig)
|
104 |
+
|
105 |
+
# Heatmap for Matrix Visualization
|
106 |
+
st.subheader("Feature Correlation Matrix")
|
107 |
+
label_encoders = {}
|
108 |
+
for col in categorical_features:
|
109 |
+
le = LabelEncoder()
|
110 |
+
df[col + '_Numeric'] = le.fit_transform(df[col])
|
111 |
+
label_encoders[col] = le
|
112 |
+
|
113 |
+
correlation_matrix = df[['Gender_Numeric', 'Purchase Amount (USD)', 'Previous Purchases', 'Frequency of Purchases_Numeric']].corr()
|
114 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
115 |
+
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', ax=ax)
|
116 |
+
st.pyplot(fig)
|
117 |
+
|
118 |
+
with tab3:
|
119 |
+
st.subheader("Enter Customer Details")
|
120 |
+
gender = st.selectbox("Gender", df['Gender'].unique())
|
121 |
+
item_purchased = st.selectbox("Item Purchased", df['Item Purchased'].unique())
|
122 |
+
previous_purchases = st.number_input("Previous Purchases", min_value=0, max_value=100, value=10)
|
123 |
+
frequency_of_purchases = st.selectbox("Frequency of Purchases", df['Frequency of Purchases'].unique().astype(str))
|
124 |
+
purchase_amount = st.number_input("Purchase Amount (USD)", min_value=1, max_value=500, value=50)
|
125 |
+
|
126 |
+
if st.button("Predict Sales Trend"):
|
127 |
+
user_input = {
|
128 |
+
'Gender': gender,
|
129 |
+
'Item Purchased': item_purchased,
|
130 |
+
'Previous Purchases': previous_purchases,
|
131 |
+
'Frequency of Purchases': frequency_of_purchases,
|
132 |
+
'Purchase Amount (USD)': purchase_amount
|
133 |
+
}
|
134 |
+
|
135 |
+
predicted_cluster = predict_cluster(user_input)
|
136 |
+
st.write(f"Predicted Cluster: {predicted_cluster}")
|
137 |
+
|
138 |
+
st.subheader(f"Sales Trend Analysis for Cluster {predicted_cluster}")
|
139 |
+
cluster_data = df[df['Cluster'] == predicted_cluster]
|
140 |
+
|
141 |
+
# Visualization of top-selling items in the cluster
|
142 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
143 |
+
sns.countplot(y=cluster_data['Item Purchased'], order=cluster_data['Item Purchased'].value_counts().index, palette='viridis', ax=ax)
|
144 |
+
ax.set_title("Top Selling Items in This Cluster")
|
145 |
+
ax.set_xlabel("Count")
|
146 |
+
ax.set_ylabel("Item Purchased")
|
147 |
+
st.pyplot(fig)
|
148 |
+
|
149 |
+
# Display average purchase amount trend
|
150 |
+
avg_purchase_amount = cluster_data.groupby('Item Purchased')['Purchase Amount (USD)'].mean()
|
151 |
+
st.write("### Average Purchase Amount for Items in This Cluster:")
|
152 |
+
st.write(avg_purchase_amount)
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
pandas
|
3 |
+
numpy
|
4 |
+
matplotlib.pyplot
|
5 |
+
seaborn
|
6 |
+
scilkt-learn
|
shopping_trends.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|