import streamlit as st import numpy as np import tensorflow as tf from PIL import Image # ---------------------------- # Config # ---------------------------- st.set_page_config(page_title="Fashion-MNIST CNN Classifier", page_icon="🧥", layout="centered") CLASS_NAMES = [ "T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot" ] MODEL_PATH = "src/fashion_mnist_cnn.keras" # ---------------------------- # Load model (cached) # ---------------------------- @st.cache_resource def load_model(): return tf.keras.models.load_model(MODEL_PATH) # ---------------------------- # Preprocess image to (1, 28, 28, 1) # ---------------------------- def preprocess_image(img: Image.Image, invert: bool = False): img = img.convert("L") # grayscale img = img.resize((28, 28)) # 28x28 arr = np.array(img).astype("float32") if invert: arr = 255.0 - arr # optional invert (useful for white background images) arr = arr / 255.0 arr = arr.reshape(1, 28, 28, 1) return arr def softmax_topk(probs, k=3): idx = np.argsort(probs)[::-1][:k] return [(CLASS_NAMES[i], float(probs[i])) for i in idx] # ---------------------------- # UI # ---------------------------- st.title("🧥 Fashion-MNIST CNN Classifier") st.write("Upload a clothing image and the CNN will predict one of 10 Fashion-MNIST classes.") # Load model try: model = load_model() except Exception as e: st.error("Model could not be loaded. Make sure `fashion_mnist_cnn.keras` is in the repo root.") st.exception(e) st.stop() st.sidebar.header("Options") invert = st.sidebar.checkbox("Invert colors (try if prediction looks wrong)", value=False) show_probs = st.sidebar.checkbox("Show probabilities", value=True) uploaded = st.file_uploader("Upload an image (PNG/JPG)", type=["png", "jpg", "jpeg"]) if uploaded is None: st.info("Please upload an image to start.") st.stop() # Display uploaded image img = Image.open(uploaded) st.image(img, caption="Uploaded image", use_container_width=True) # Preprocess + predict x = preprocess_image(img, invert=invert) probs = model.predict(x, verbose=0)[0] pred_idx = int(np.argmax(probs)) pred_label = CLASS_NAMES[pred_idx] pred_conf = float(probs[pred_idx]) st.subheader("Prediction") st.write(f"**Predicted class:** {pred_label}") st.write(f"**Confidence:** {pred_conf:.3f}") # Show top-3 top3 = softmax_topk(probs, k=3) st.write("**Top 3:**") for name, p in top3: st.write(f"- {name}: {p:.3f}") # Probability chart if show_probs: st.subheader("Class Probabilities") chart_data = {CLASS_NAMES[i]: float(probs[i]) for i in range(10)} st.bar_chart(chart_data) st.caption("Tip: Fashion-MNIST images are 28×28 grayscale. For real photos, results may vary.")