LargeScaleFishClassification / src /streamlit_app.py
EnYa32's picture
Update src/streamlit_app.py
8cabf80 verified
Raw History Blame
4.38 kB
# --- Fish Classifier (CNN from scratch) ---------------------------------------
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
import tensorflow as tf
from tensorflow.keras.models import load_model
# -----------------------------------------------------------------------------
# PAGE CONFIG
# -----------------------------------------------------------------------------
st.set_page_config(
page_title="Fish Classifier (CNN – From Scratch)",
layout="centered"
)
# -----------------------------------------------------------------------------
# SETTINGS
# -----------------------------------------------------------------------------
MODEL_PATH = "src/best_fish_cnn_new.keras"
IMG_SIZE = (224, 224)
CLASS_NAMES = [
"Black Sea Sprat",
"Gilt-Head Bream",
"Horse Mackerel",
"Red Mullet",
"Red Sea Bream",
"Sea Bass",
"Shrimp",
"Striped Red Mullet",
"Trout"
]
# -----------------------------------------------------------------------------
# MODEL LOADING (CACHED)
# -----------------------------------------------------------------------------
@st.cache_resource
def load_model_cached():
model = tf.keras.models.load_model(MODEL_PATH, compile=False)
return model
model = load_model_cached()
# -----------------------------------------------------------------------------
# HELPER FUNCTIONS
# -----------------------------------------------------------------------------
def preprocess_image(image: Image.Image) -> np.ndarray:
"""Resize and normalize image for the CNN model."""
image = image.convert("RGB")
image = image.resize(IMG_SIZE)
img_array = np.array(image).astype("float32") / 255.0
img_array = np.expand_dims(img_array, axis=0)
return img_array
def predict_image(image: Image.Image):
"""Run model prediction and return class label and probability vector."""
img_batch = preprocess_image(image)
preds = model.predict(img_batch)
probs = preds[0]
pred_index = int(np.argmax(probs))
pred_class = CLASS_NAMES[pred_index]
return pred_class, probs
# -----------------------------------------------------------------------------
# UI – HEADER
# -----------------------------------------------------------------------------
st.title("🐟 Fish Species Classifier (CNN From Scratch)")
st.write(
"Upload a fish image and the model will predict one of **9 fish species**. "
"This model is a custom Convolutional Neural Network (**no transfer learning**) "
"trained on the Kaggle fish dataset."
)
# -----------------------------------------------------------------------------
# SIDEBAR INFO
# -----------------------------------------------------------------------------
st.sidebar.header("ℹ️ About this app")
st.sidebar.markdown(
"""
**Model:** Custom CNN (no transfer learning)
**Input size:** 224 Γ— 224
**Classes:** 9 fish species
**Validation performance:**
- Accuracy: ~84%
- Top-3 accuracy: ~95%
**Author:** Enes Yamac
"""
)
# -----------------------------------------------------------------------------
# FILE UPLOAD
# -----------------------------------------------------------------------------
uploaded_file = st.file_uploader(
"πŸ“€ Upload a fish image (JPG/PNG)",
type=["jpg", "jpeg", "png"]
)
# -----------------------------------------------------------------------------
# PREDICTION + OUTPUT
# -----------------------------------------------------------------------------
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded image", use_container_width=True)
with st.spinner("πŸ” Predicting..."):
pred_class, probs = predict_image(image)
st.subheader("πŸ”Ž Prediction")
st.write(f"**Predicted class:** `{pred_class}`")
# Wahrscheinlichkeiten vorbereiten
prob_dict = {cls: float(p) for cls, p in zip(CLASS_NAMES, probs)}
prob_df = (
pd.DataFrame.from_dict(prob_dict, orient="index", columns=["Probability"])
.sort_values("Probability", ascending=False)
)
st.subheader("πŸ“Š Class probabilities")
st.bar_chart(prob_df)
with st.expander("Show numeric probabilities"):
st.dataframe(prob_df.style.format("{:.2%}"))
else:
st.info("Please upload an image to start.")