-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
140 lines (113 loc) · 4.04 KB
/
Copy pathapp.py
File metadata and controls
140 lines (113 loc) · 4.04 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# ==========================================================
# 👨💻 K. Siddhartha — Python Developer | AI / NLP Developer
# Product Category Prediction using Decision Tree
# ==========================================================
import numpy as np
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
# ==========================================================
# PAGE CONFIG
# ==========================================================
st.set_page_config(
page_title="Product Category Prediction | Decision Tree",
layout="centered"
)
st.title("🛍️ Product Category Prediction using Decision Tree")
st.caption(
"Supervised Machine Learning • Explainable AI • Decision Tree Visualization"
)
# ==========================================================
# DATASET (CACHED)
# ==========================================================
@st.cache_data
def load_data():
data = {
"price": [1000, 1200, 900, 50, 60, 40, 10, 15, 8],
"weight": [1.5, 1.3, 1.8, 0.5, 0.6, 0.4, 0.3, 0.2, 0.1],
"rating": [4.5, 4.2, 4.7, 3.8, 4.0, 3.5, 4.8, 4.6, 4.9],
"category": [
"Electronics", "Electronics", "Electronics",
"Clothing", "Clothing", "Clothing",
"Grocery", "Grocery", "Grocery"
]
}
return pd.DataFrame(data)
df = load_data()
st.subheader("📊 Training Dataset")
st.dataframe(df, use_container_width=True)
# ==========================================================
# SPLIT DATA
# ==========================================================
X = df[["price", "weight", "rating"]]
y = df["category"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.3,
random_state=42,
stratify=y
)
# ==========================================================
# MODEL TRAINING (CACHED RESOURCE)
# ==========================================================
@st.cache_resource
def train_model(X_train, y_train):
model = DecisionTreeClassifier(
max_depth=3,
random_state=42
)
model.fit(X_train, y_train)
return model
model = train_model(X_train, y_train)
# ==========================================================
# MODEL PERFORMANCE
# ==========================================================
st.subheader("📈 Model Performance")
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
st.metric("Model Accuracy", f"{accuracy:.2f}")
with st.expander("📄 Classification Report"):
report = classification_report(y_test, y_pred, output_dict=True)
st.dataframe(pd.DataFrame(report).transpose())
# ==========================================================
# USER INPUT
# ==========================================================
st.subheader("🔮 Predict Product Category")
col1, col2 = st.columns(2)
with col1:
price = st.number_input("Price", 1.0, 2000.0, 100.0)
with col2:
weight = st.number_input("Weight (kg)", 0.1, 5.0, 0.5)
rating = st.slider("Rating", 1.0, 5.0, 4.0)
if st.button("Predict Category"):
pred = model.predict([[price, weight, rating]])[0]
prob = model.predict_proba([[price, weight, rating]])[0]
st.success(f"Predicted Category: **{pred}**")
st.info(f"Confidence: {np.max(prob)*100:.2f}%")
# ==========================================================
# DECISION TREE VISUALIZATION (XAI)
# ==========================================================
st.subheader("🌳 Decision Tree Explainability")
fig, ax = plt.subplots(figsize=(10, 5))
plot_tree(
model,
feature_names=["Price", "Weight", "Rating"],
class_names=model.classes_,
filled=True,
rounded=True,
impurity=False,
ax=ax
)
ax.set_axis_off()
st.pyplot(fig)
# ==========================================================
# FOOTER
# ==========================================================
st.markdown("---")
st.markdown(
"Built with **Streamlit**, **Scikit-learn**, and **Matplotlib**"
)