File size: 3,375 Bytes
cd3538a | 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 97 98 99 100 101 102 103 104 105 106 107 108 | import streamlit as st
import torch
import torch.nn as nn
import torchvision.models as models
from PIL import Image
from torchvision import transforms
import gradio as gr
import plotly.graph_objects as go
# Device setup
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Image transformations
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # ImageNet standard
])
# Initialize models
def load_models():
# Load models (ResNet, MobileNetV2)
resnet18 = models.resnet18(pretrained=False)
resnet18.fc = nn.Linear(resnet18.fc.in_features, 11) # Modify output layer for 11 classes
resnet18.load_state_dict(torch.load('models/resnet18_fish_classification_model.pth'))
resnet18.to(device)
mobilenet_v2 = models.mobilenet_v2(pretrained=False)
mobilenet_v2.classifier[1] = nn.Linear(1280, 11) # Modify output layer for 11 classes
mobilenet_v2.load_state_dict(torch.load('models/mobilenetv2_fish_classification_model.pth'))
mobilenet_v2.to(device)
models_dict = {
'ResNet18': resnet18,
'MobileNetV2': mobilenet_v2
}
return models_dict
# Image prediction function
def predict_image(image):
models_dict = load_models()
image = transform(image).unsqueeze(0).to(device)
predictions = {}
for model_name, model in models_dict.items():
model.eval()
with torch.no_grad():
outputs = model(image)
probabilities = torch.nn.functional.softmax(outputs, dim=1)
_, predicted_class = torch.max(probabilities, 1)
confidence = probabilities[0, predicted_class].item()
predictions[model_name] = {'predicted_class': predicted_class.item(), 'confidence': confidence}
return predictions
# Confidence chart creation
def create_confidence_chart(confidence, label):
fig = go.Figure(go.Bar(
x=[confidence, 100-confidence],
y=[label, 'Other'],
orientation='h',
marker_color=['#667eea', '#e0e0e0'],
text=[f'{confidence:.1f}%', f'{100-confidence:.1f}%'],
textposition='inside',
textfont=dict(color='white', size=14)
))
fig.update_layout(
title=f"Prediction Confidence: {label}",
xaxis_title="Confidence (%)",
height=200,
margin=dict(l=0, r=0, t=40, b=0),
showlegend=False,
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)'
)
return fig
# Gradio Interface
def gradio_interface():
# This will load the models and use Gradio's interface to interact
models_dict = load_models()
gradio_interface = gr.Interface(
fn=predict_image,
inputs=gr.inputs.Image(type="pil"),
outputs=gr.outputs.JSON(),
live=True,
title="Fish Image Classification",
description="Classify fish images using AI models (ResNet18, MobileNetV2).",
)
return gradio_interface
# Streamlit UI
st.title("Fish Image Classification with AI")
st.markdown("""
This app allows you to upload a fish image, and it will classify the fish into one of the categories using two different AI models:
- **ResNet18**
- **MobileNetV2**
Upload an image below to get predictions.
""")
gradio_interface().launch(inline=True)
|