Spaces:
Sleeping
Sleeping
Upload 5 files
Browse filesFiles changed (5)
- app.pyAdded+59
- class_names.txtAdded+101
- model.pyAdded+33
- pretrained_effnetb2_feature_extractor_food101_20_percent.pthAdded+3
- requirements.txtAdded+3
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import gradio as grimport osimport torch
from model import create_effnetb2_modelfrom timeit import default_timer as timerfrom typing import Tuple, Dict
with open("class_names.txt", "r") as f: class_names = [food_name.strip() for food_name in f.readlines()]
effnetb2, effnetb2_transforms = create_effnetb2_model( num_classes=101,)
effnetb2.load_state_dict( torch.load( f="pretrained_effnetb2_feature_extractor_food101_20_percent.pth", map_location=torch.device("cpu"), ))
def predict(img) -> Tuple[Dict, float]: """Transforms and performs a prediction on img and returns prediction and time taken. """ start_time = timer() img = effnetb2_transforms(img).unsqueeze(0) effnetb2.eval() with torch.inference_mode(): pred_probs = torch.softmax(effnetb2(img), dim=1) pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))} pred_time = round(timer() - start_time, 5) return pred_labels_and_probs, pred_time
title = "Food Image Classifier ๐ ๐ ๐ฎ ๐ฐ"description = "An EfficientNetB2 model that classifies images of food into [101 different classes](https://github.com/TensorCruncher/food-image-classifier/blob/main/data/food101_class_names.txt)."article = "View on [GitHub](https://github.com/TensorCruncher/food-image-classifier)."
example_list = [["examples/" + example] for example in os.listdir("examples")]
demo = gr.Interface( fn=predict, inputs=gr.Image(type="pil"), outputs=[ gr.Label(num_top_classes=5, label="Predictions"), gr.Number(label="Prediction time (s)"), ], examples=example_list, title=title, description=description, article=article,)
demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101apple_piebaby_back_ribsbaklavabeef_carpacciobeef_tartarebeet_saladbeignetsbibimbapbread_puddingbreakfast_burritobruschettacaesar_saladcannolicaprese_saladcarrot_cakecevichecheese_platecheesecakechicken_currychicken_quesadillachicken_wingschocolate_cakechocolate_moussechurrosclam_chowderclub_sandwichcrab_cakescreme_bruleecroque_madamecup_cakesdeviled_eggsdonutsdumplingsedamameeggs_benedictescargotsfalafelfilet_mignonfish_and_chipsfoie_grasfrench_friesfrench_onion_soupfrench_toastfried_calamarifried_ricefrozen_yogurtgarlic_breadgnocchigreek_saladgrilled_cheese_sandwichgrilled_salmonguacamolegyozahamburgerhot_and_sour_souphot_doghuevos_rancheroshummusice_creamlasagnalobster_bisquelobster_roll_sandwichmacaroni_and_cheesemacaronsmiso_soupmusselsnachosomeletteonion_ringsoysterspad_thaipaellapancakespanna_cottapeking_duckphopizzapork_choppoutineprime_ribpulled_pork_sandwichramenraviolired_velvet_cakerisottosamosasashimiscallopsseaweed_saladshrimp_and_gritsspaghetti_bolognesespaghetti_carbonaraspring_rollssteakstrawberry_shortcakesushitacostakoyakitiramisutuna_tartarewaffles123456789101112131415161718192021222324252627282930313233import torchimport torchvision
from torch import nn
def create_effnetb2_model(num_classes:int=3, seed:int=42): """Creates an EfficientNetB2 feature extractor model and transforms.
Args: num_classes (int, optional): number of classes in the classifier head. Defaults to 3. seed (int, optional): random seed value. Defaults to 42.
Returns: model (torch.nn.Module): EffNetB2 feature extractor model. transforms (torchvision.transforms): EffNetB2 image transforms. """ weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT transforms = weights.transforms() model = torchvision.models.efficientnet_b2(weights=weights)
for param in model.parameters(): param.requires_grad = False
torch.manual_seed(seed) model.classifier = nn.Sequential( nn.Dropout(p=0.3, inplace=True), nn.Linear(in_features=1408, out_features=num_classes), ) return model, transforms123version https://git-lfs.github.com/spec/v1oid sha256:1f3e3984ed67651302781fbc4a452a3f92c2781d11251d6f7d5817f799ff9d0fsize 31855674123torchtorchvisiongradioapp.pyAdded+59
class_names.txtAdded+101
model.pyAdded+33
pretrained_effnetb2_feature_extractor_food101_20_percent.pthAdded+3
requirements.txtAdded+3