File size: 2,830 Bytes
f7549c3
7066a29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7549c3
7066a29
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
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.")