MobilePriceClassification / src /streamlit_app.py
EnYa32's picture
Update src/streamlit_app.py
53cfa87 verified
Raw History Blame Contribute Delete
3.15 kB
import streamlit as st
import numpy as np
import pandas as pd
import joblib
st.set_page_config(page_title="Smartphone Price Range Classification", page_icon="📱", layout="wide")
@st.cache_resource
def load_artifacts():
model = joblib.load("src/knn_model.pkl")
scaler = joblib.load("src/scalerknn.pkl")
features = joblib.load("src/model_features.pkl")
return model, scaler, features
model, scaler, feature_names = load_artifacts()
PRICE_LABELS = {
0: "Low Cost",
1: "Medium Cost",
2: "High Cost",
3: "Very High Cost"
}
st.title("📱 Smartphone Price Range Classification")
st.write(
"This app predicts the **price range** of a smartphone based on its technical specifications "
"using a **K-Nearest Neighbors (KNN)** model."
)
with st.sidebar:
st.header("Input Features")
use_example = st.checkbox("Use example values", value=True)
# Sensible defaults (example-like)
default_vals = {
"battery_power": 1000,
"blue": 1,
"clock_speed": 1.5,
"dual_sim": 1,
"fc": 5,
"four_g": 1,
"int_memory": 32,
"m_dep": 0.5,
"mobile_wt": 150,
"n_cores": 4,
"pc": 12,
"px_height": 1000,
"px_width": 1800,
"ram": 3000,
"sc_h": 14,
"sc_w": 7,
"talk_time": 12,
"three_g": 1,
"touch_screen": 1,
"wifi": 1
}
inputs = {}
for f in feature_names:
# fallback if feature not in defaults
base = default_vals.get(f, 0)
if f in ["blue", "dual_sim", "four_g", "three_g", "touch_screen", "wifi"]:
inputs[f] = st.selectbox(f, [0, 1], index=int(base))
elif f in ["clock_speed", "m_dep"]:
inputs[f] = st.number_input(f, value=float(base), min_value=0.0, step=0.1)
else:
inputs[f] = st.number_input(f, value=float(base), min_value=0.0, step=1.0)
st.caption("Tip: Keep the same feature meaning as in the dataset.")
# Build input dataframe in correct order
X_input = pd.DataFrame([[inputs[f] for f in feature_names]], columns=feature_names)
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("Your input")
st.dataframe(X_input, use_container_width=True)
with col2:
st.subheader("Prediction")
# Scale then predict
X_scaled = scaler.transform(X_input.values)
pred_class = int(model.predict(X_scaled)[0])
pred_label = PRICE_LABELS.get(pred_class, str(pred_class))
st.metric("Predicted Price Range", f"{pred_class} — {pred_label}")
# Probabilities (if available)
if hasattr(model, "predict_proba"):
proba = model.predict_proba(X_scaled)[0]
proba_df = pd.DataFrame(
{"Class": list(range(len(proba))),
"Label": [PRICE_LABELS.get(i, str(i)) for i in range(len(proba))],
"Probability": proba}
).sort_values("Probability", ascending=False)
st.write("Class probabilities:")
st.dataframe(proba_df, use_container_width=True)
st.divider()
st.write(
"Model files expected in the same folder: `knn_model.pkl`, `scaler.pkl`, `model_features.pkl`."
)