File size: 1,501 Bytes
5b76da8 165427e 5b76da8 | 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 | import gradio as gr
import tensorflow as tf
import numpy as np
from PIL import Image
# =========================
# 1. Load Model
# =========================
model = tf.keras.models.load_model("cnn_model_transfer.keras")
# Class labels (match training order)
class_names = ["Cat", "Dog"]
# =========================
# 2. Preprocess Function
# =========================
def preprocess_image(img):
img = img.resize((224, 224)) # MobileNetV2 size
img = np.array(img)
# Apply same preprocessing used during training
img = tf.keras.applications.mobilenet_v2.preprocess_input(img)
img = np.expand_dims(img, axis=0)
return img
# =========================
# 3. Prediction Function
# =========================
def predict(img):
img_array = preprocess_image(img)
pred = model.predict(img_array)[0][0]
if pred > 0.5:
label = class_names[1]
confidence = float(pred)
else:
label = class_names[0]
confidence = float(1 - pred)
return {
"Cat": 1 - pred,
"Dog": pred
}
# =========================
# 4. Gradio Interface
# =========================
demo = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil"),
outputs=gr.Label(num_top_classes=2),
title="🐱🐶 Cat vs Dog Classifier",
description="Upload an image and the model will predict whether it is a Cat or Dog using MobileNetV2 Transfer Learning."
)
# =========================
# 5. LauncH
# =========================
demo.launch() |