Spaces:
Build error
Build error
File size: 5,455 Bytes
567099f 0395eb2 567099f 0395eb2 f00614d 0395eb2 f00614d 0395eb2 a5daa3d 567099f |
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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
import gradio as gr
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.preprocessing import LabelEncoder
import torch
import torch.nn.functional as F
import torchvision
from torchvision import transforms
import torchvision.models as models
from torchvision.datasets import ImageFolder
from torch.utils.data.dataset import Dataset
from torch.utils.data import Dataset, random_split, DataLoader
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
import torchmetrics
from tqdm.notebook import tqdm
class ImageClassificationBase(torch.nn.Module):
# training step
def training_step(self, batch):
img, targets = batch
out = self(img)
loss = F.nll_loss(out, targets)
return loss
# validation step
def validation_step(self, batch):
img, targets = batch
out = self(img)
loss = F.nll_loss(out, targets)
acc = accuracy(out, targets)
return {'val_acc':acc.detach(), 'val_loss':loss.detach()}
# validation epoch end
def validation_epoch_end(self, outputs):
batch_losses = [x['val_loss'] for x in outputs]
epoch_loss = torch.stack(batch_losses).mean()
batch_accs = [x['val_acc'] for x in outputs]
epoch_acc = torch.stack(batch_accs).mean()
return {'val_loss':epoch_loss.item(), 'val_acc':epoch_acc.item()}
# print result end epoch
def epoch_end(self, epoch, result):
print("Epoch [{}] : train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result["train_loss"], result["val_loss"], result["val_acc"]))
class DogBreedPretrainedWideResnet(ImageClassificationBase):
def __init__(self):
super().__init__()
self.network = models.wide_resnet50_2(pretrained=True)
# Replace last layer
num_ftrs = self.network.fc.in_features
self.network.fc = torch.nn.Sequential(
torch.nn.Linear(num_ftrs, 120),
torch.nn.LogSoftmax(dim=1)
)
def forward(self, xb):
return self.network(xb)
def predict_single(img):
xb = img.unsqueeze(0) # adding extra dimension
xb = to_device(xb, device)
preds = model(xb) # change model object here
predictions = preds[0]
max_val, kls = torch.max(predictions, dim=0)
print('Predicted :', breeds[kls])
plt.imshow(img.permute(1,2,0))
plt.show()
def get_default_device():
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
def to_device(data, device):
if isinstance(data, (list, tuple)):
return [to_device(d, device) for d in data]
else:
return data.to(device, non_blocking=True)
def accuracy(outputs, labels):
_, preds = torch.max(outputs, dim=1)
return torch.tensor(torch.sum(preds == labels).item() / len(preds))
def image_mod(image):
return predict_single(image)
device = get_default_device()
PATH = "./model/model.zip"
model = DogBreedPretrainedWideResnet()
model.load_state_dict(torch.load(PATH))
breeds=['Chihuahua',
'Japanese spaniel',
'Maltese dog',
'Pekinese',
'Shih Tzu',
'Blenheim spaniel',
'papillon',
'toy terrier',
'Rhodesian ridgeback',
'Afghan hound',
'basset',
'beagle',
'bloodhound',
'bluetick',
'black and tan coonhound',
'Walker hound',
'English foxhound',
'redbone',
'borzoi',
'Irish wolfhound',
'Italian greyhound',
'whippet',
'Ibizan hound',
'Norwegian elkhound',
'otterhound',
'Saluki',
'Scottish deerhound',
'Weimaraner',
'Staffordshire bullterrier',
'American Staffordshire terrier',
'Bedlington terrier',
'Border terrier',
'Kerry blue terrier',
'Irish terrier',
'Norfolk terrier',
'Norwich terrier',
'Yorkshire terrier',
'wire haired fox terrier',
'Lakeland terrier',
'Sealyham terrier',
'Airedale',
'cairn',
'Australian terrier',
'Dandie Dinmont',
'Boston bull',
'miniature schnauzer',
'giant schnauzer',
'standard schnauzer',
'Scotch terrier',
'Tibetan terrier',
'silky terrier',
'soft coated wheaten terrier',
'West Highland white terrier',
'Lhasa',
'flat coated retriever',
'curly coated retriever',
'golden retriever',
'Labrador retriever',
'Chesapeake Bay retriever',
'German short haired pointer',
'vizsla',
'English setter',
'Irish setter',
'Gordon setter',
'Brittany spaniel',
'clumber',
'English springer',
'Welsh springer spaniel',
'cocker spaniel',
'Sussex spaniel',
'Irish water spaniel',
'kuvasz',
'schipperke',
'groenendael',
'malinois',
'briard',
'kelpie',
'komondor',
'Old English sheepdog',
'Shetland sheepdog',
'collie',
'Border collie',
'Bouvier des Flandres',
'Rottweiler',
'German shepherd',
'Doberman',
'miniature pinscher',
'Greater Swiss Mountain dog',
'Bernese mountain dog',
'Appenzeller',
'EntleBucher',
'boxer',
'bull mastiff',
'Tibetan mastiff',
'French bulldog',
'Great Dane',
'Saint Bernard',
'Eskimo dog',
'malamute',
'Siberian husky',
'affenpinscher',
'basenji',
'pug',
'Leonberg',
'Newfoundland',
'Great Pyrenees',
'Samoyed',
'Pomeranian',
'chow',
'keeshond',
'Brabancon griffon',
'Pembroke',
'Cardigan',
'toy poodle',
'miniature poodle',
'standard poodle',
'Mexican hairless',
'dingo',
'dhole',
'African hunting dog']
iface = gr.Interface(image_mod, gr.Image(type="pil"), "image")
iface.launch() |