Update app.py
Browse files
app.py
CHANGED
|
@@ -5,100 +5,72 @@ from sklearn.cluster import KMeans
|
|
| 5 |
from sklearn.preprocessing import StandardScaler
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import seaborn as sns
|
| 8 |
-
import requests
|
| 9 |
|
| 10 |
# App title
|
| 11 |
st.title("🛍️ Customer Segmentation Tool")
|
| 12 |
|
| 13 |
-
|
|
|
|
| 14 |
|
| 15 |
# About Tab
|
| 16 |
with tab1:
|
| 17 |
st.write("""
|
| 18 |
-
This app uses unsupervised learning techniques to segment customers based on their purchasing behavior.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
""")
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
if uploaded_file is not None:
|
| 26 |
-
try:
|
| 27 |
-
if uploaded_file.name.endswith('.csv'):
|
| 28 |
-
df = pd.read_csv(uploaded_file, encoding='ISO-8859-1', on_bad_lines='skip')
|
| 29 |
-
elif uploaded_file.name.endswith('.xlsx'):
|
| 30 |
-
df = pd.read_excel(uploaded_file)
|
| 31 |
-
else:
|
| 32 |
-
st.error("Unsupported file format. Please upload a CSV or Excel file.")
|
| 33 |
-
st.stop()
|
| 34 |
-
|
| 35 |
-
st.write("### Dataset Overview")
|
| 36 |
-
st.write(df.head())
|
| 37 |
-
except Exception as e:
|
| 38 |
-
st.error(f"Error loading dataset: {e}")
|
| 39 |
-
st.stop()
|
| 40 |
-
|
| 41 |
-
st.write("### Columns detected in your dataset:")
|
| 42 |
-
st.write(df.columns.tolist())
|
| 43 |
-
|
| 44 |
-
customer_col = st.selectbox("Select Customer Column", df.columns.tolist())
|
| 45 |
-
quantity_col = st.selectbox("Select Quantity Column", df.columns.tolist())
|
| 46 |
-
unit_price_col = st.selectbox("Select Unit Price Column", df.columns.tolist())
|
| 47 |
-
|
| 48 |
-
if customer_col not in df.columns or quantity_col not in df.columns or unit_price_col not in df.columns:
|
| 49 |
-
st.error("One or more selected columns do not exist in the dataset. Please select valid columns.")
|
| 50 |
-
st.stop()
|
| 51 |
-
|
| 52 |
-
df = df.dropna(subset=[customer_col])
|
| 53 |
-
df["TotalSpent"] = pd.to_numeric(df[quantity_col], errors='coerce') * pd.to_numeric(df[unit_price_col], errors='coerce')
|
| 54 |
-
df = df.dropna(subset=["TotalSpent"])
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
# Customer Segmentation Tab
|
| 78 |
with tab3:
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
data=csv,
|
| 100 |
-
file_name="segmented_customer_data.csv",
|
| 101 |
-
mime="text/csv"
|
| 102 |
-
)
|
| 103 |
-
else:
|
| 104 |
-
st.write("Please upload a dataset to start.")
|
|
|
|
| 5 |
from sklearn.preprocessing import StandardScaler
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import seaborn as sns
|
|
|
|
| 8 |
|
| 9 |
# App title
|
| 10 |
st.title("🛍️ Customer Segmentation Tool")
|
| 11 |
|
| 12 |
+
# 🎯 Streamlit Tabs
|
| 13 |
+
tab1, tab2, tab3 = st.tabs(["📖 About", "📊 Dataset Overview", "🧑🤝🧑 Customer Segmentation"])
|
| 14 |
|
| 15 |
# About Tab
|
| 16 |
with tab1:
|
| 17 |
st.write("""
|
| 18 |
+
This app uses unsupervised learning techniques to segment customers based on their purchasing behavior.
|
| 19 |
+
The dataset is preloaded and contains online retail data.
|
| 20 |
+
### How It Works:
|
| 21 |
+
- **Step 1**: Load customer transaction data, including details like Quantity, UnitPrice, and CustomerID.
|
| 22 |
+
- **Step 2**: Process the data by calculating the total spent and aggregating the information by customer.
|
| 23 |
+
- **Step 3**: Apply **K-Means Clustering** to segment the customers into distinct groups.
|
| 24 |
+
- **Step 4**: Visualize the customer segments with a scatter plot.
|
| 25 |
""")
|
| 26 |
|
| 27 |
+
# Load preloaded dataset
|
| 28 |
+
file_path = "/mnt/data/Online Retail.xlsx"
|
| 29 |
+
df = pd.read_excel(file_path, sheet_name='Online Retail')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# Dataset Overview Tab
|
| 32 |
+
with tab2:
|
| 33 |
+
st.write("### Dataset Overview")
|
| 34 |
+
st.write(df.head())
|
| 35 |
+
|
| 36 |
+
# Preprocess data
|
| 37 |
+
df = df.dropna(subset=["CustomerID"]) # Remove rows without CustomerID
|
| 38 |
+
df["TotalSpent"] = pd.to_numeric(df["Quantity"], errors='coerce') * pd.to_numeric(df["UnitPrice"], errors='coerce')
|
| 39 |
+
df = df.dropna(subset=["TotalSpent"])
|
| 40 |
+
|
| 41 |
+
# Aggregate data by Customer
|
| 42 |
+
customer_data = df.groupby("CustomerID").agg({
|
| 43 |
+
"TotalSpent": "sum",
|
| 44 |
+
"Quantity": "sum",
|
| 45 |
+
"UnitPrice": "mean"
|
| 46 |
+
}).rename(columns={"Quantity": "NumTransactions", "UnitPrice": "AvgUnitPrice"})
|
| 47 |
+
|
| 48 |
+
st.write("### Processed Customer Data")
|
| 49 |
+
st.write(customer_data.head())
|
| 50 |
+
|
| 51 |
+
# Standardize the data
|
| 52 |
+
scaler = StandardScaler()
|
| 53 |
+
customer_scaled = pd.DataFrame(scaler.fit_transform(customer_data), columns=customer_data.columns, index=customer_data.index)
|
| 54 |
|
| 55 |
# Customer Segmentation Tab
|
| 56 |
with tab3:
|
| 57 |
+
# User selects the number of clusters
|
| 58 |
+
num_clusters = st.slider("Select Number of Clusters", min_value=2, max_value=10, value=3)
|
| 59 |
+
|
| 60 |
+
# Apply K-Means clustering
|
| 61 |
+
model = KMeans(n_clusters=num_clusters, random_state=42)
|
| 62 |
+
customer_data["Cluster"] = model.fit_predict(customer_scaled)
|
| 63 |
+
|
| 64 |
+
# Visualize the clusters
|
| 65 |
+
st.write("### Clusters Visualization")
|
| 66 |
+
fig, ax = plt.subplots()
|
| 67 |
+
scatter = ax.scatter(customer_data["TotalSpent"], customer_data["NumTransactions"], c=customer_data["Cluster"], cmap='viridis')
|
| 68 |
+
ax.set_xlabel("Total Spent")
|
| 69 |
+
ax.set_ylabel("Number of Transactions")
|
| 70 |
+
ax.set_title("Customer Segments")
|
| 71 |
+
plt.colorbar(scatter, label="Cluster")
|
| 72 |
+
st.pyplot(fig)
|
| 73 |
+
|
| 74 |
+
# Show the segmented customer data
|
| 75 |
+
st.write("### Customer Segments Data")
|
| 76 |
+
st.write(customer_data.head())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|