Spaces:
Runtime error
Runtime error
andreasmlanger
commited on
Commit
•
7de1996
1
Parent(s):
733c4ae
initial commit
Browse files- app.py +47 -0
- cat_dog_RNN.pth +3 -0
- examples/01.jpg +0 -0
- examples/02.jpg +0 -0
- examples/03.jpg +0 -0
- examples/04.jpg +0 -0
- requirements.txt +3 -0
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Simple Gradio app on http://127.0.0.1:7860
|
3 |
+
Hugging Face: https://huggingface.co/spaces/andreasmlanger/cat_dog
|
4 |
+
"""
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
import torch
|
8 |
+
from torch import nn
|
9 |
+
from torchvision import models, transforms
|
10 |
+
import os
|
11 |
+
|
12 |
+
|
13 |
+
MODEL_PATH = r'cat_dog_RNN.pth' # path to trained model, needs to be in same directory
|
14 |
+
EXAMPLES = [[os.path.join('examples', f)] for f in os.listdir('examples')] # example images
|
15 |
+
CLASS_NAMES = ['cat', 'dog']
|
16 |
+
|
17 |
+
# Load model architecture and saved weights
|
18 |
+
model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
|
19 |
+
for param in model.parameters():
|
20 |
+
param.requires_grad = False # freeze pre-trained weights, so they don't get changed during training
|
21 |
+
model.fc = nn.Sequential(
|
22 |
+
nn.Linear(in_features=model.fc.in_features, out_features=512),
|
23 |
+
nn.ReLU(),
|
24 |
+
nn.Dropout(0.2),
|
25 |
+
nn.Linear(512, len(CLASS_NAMES), bias=True)
|
26 |
+
)
|
27 |
+
model.load_state_dict(torch.load(MODEL_PATH))
|
28 |
+
|
29 |
+
|
30 |
+
def predict(img):
|
31 |
+
transform = transforms.Compose([transforms.Resize(size=(224, 224)), transforms.ToTensor()])
|
32 |
+
transformed_image = transform(img).unsqueeze(0)
|
33 |
+
model.eval()
|
34 |
+
with torch.inference_mode():
|
35 |
+
pred_probs = torch.softmax(model(transformed_image), dim=1)
|
36 |
+
return {CLASS_NAMES[i]: float(pred_probs[0][i]) for i in range(len(CLASS_NAMES))}
|
37 |
+
|
38 |
+
|
39 |
+
# Create and launch the Gradio demo
|
40 |
+
demo = gr.Interface(fn=predict,
|
41 |
+
inputs=gr.Image(type='pil', label='Image'),
|
42 |
+
outputs=[gr.Label(num_top_classes=2, label='Predictions')],
|
43 |
+
examples=EXAMPLES,
|
44 |
+
title='Cat vs Dog Image Classifier',
|
45 |
+
description='A residual neuronal network designed to distinguish between cat and dog images.')
|
46 |
+
|
47 |
+
demo.launch(debug=False)
|
cat_dog_RNN.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8e2fe3ae139b6b5ad651d6de59f8a8e3b88de786a9fd638bcfc8356b65bb397b
|
3 |
+
size 98549674
|
examples/01.jpg
ADDED
examples/02.jpg
ADDED
examples/03.jpg
ADDED
examples/04.jpg
ADDED
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
gradio==4.16.0
|
2 |
+
torch==2.1.2
|
3 |
+
torchvision==0.16.2
|