Spaces:
Sleeping
Sleeping
First commit
Browse filesFiles changed (8)
- 07_effnetb2_data_50_percent_10_epochs.pthAdded+3
- 09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pthAdded+3
- app.pyAdded+91
- examples/140016.jpgAdded
- examples/647683.jpgAdded
- examples/715227.jpgAdded
- model.pyAdded+44
- requirements.txtAdded+4
123version https://git-lfs.github.com/spec/v1oid sha256:9dc265ff27b5ff26522a292f8039b4c910a49f4a8754ef4b90aafc7d1f00f9f6size 31273033123version https://git-lfs.github.com/spec/v1oid sha256:e65879e63a119f1dcc76e8928790aac49373e4bc1d29c0208b7e7c6f88dee2bbsize 3127303312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
### 1. Imports and class names setup ###import gradio as grimport osimport torchimport torchvision.transforms as T
from model import create_effnet_b2from timeit import default_timer as timerfrom typing import Tuple, Dict
# Setup class namesclass_names = ['pizza', 'steak', 'sushi']
### 2. Model and transforms preparation ###test_tsfm = T.Compose([T.Resize((224,224)), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], # 3. A mean of [0.485, 0.456, 0.406] (across each colour channel) std=[0.229, 0.224, 0.225]) # 4. A standard deviation of [0.229, 0.224, 0.225] (across each colour channel), ])
# Create EffNetB2 Modeleffnetb2, test_transform = create_effnet_b2(num_of_class=len(class_names), transform=test_tsfm, seed=42)
# saved_path = 'demos\foodvision_mini\09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth'saved_path = '07_effnetb2_data_50_percent_10_epochs.pth'
print('Loading Model State Dictionary')# Load saved weightseffnetb2.load_state_dict( torch.load(f=saved_path, map_location=torch.device('cpu'), # load to CPU ) )
print('Model Loaded ...')### 3. Predict function ###
# Create predict functionfrom typing import Tuple, Dict
def predict(img) -> Tuple[Dict, float]: """Transforms and performs a prediction on img and returns prediction and time taken. """ # Start the timer start_time = timer() # Transform the target image and add a batch dimension img = test_tsfm(img).unsqueeze(0) # Put model into evaluation mode and turn on inference mode effnetb2.eval() with torch.inference_mode(): # Pass the transformed image through the model and turn the prediction logits into prediction probabilities pred_probs = torch.softmax(effnetb2(img), dim=1) # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter) pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))} # Calculate the prediction time pred_time = round(timer() - start_time, 5) # Return the prediction dictionary and prediction time return pred_labels_and_probs, pred_time
### 4. Gradio App ###
# Create title, description and article stringstitle= 'FoodVision Mini 🍕🥩🍣'description = "An EfficientNetB2 feature extractor computer vision model to classify images of food as pizza, steak or sushi."article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
# Create examples list from "examples/" directoryexample_list = [["examples/" + example] for example in os.listdir("examples")]
# Create the Gradio demodemo = gr.Interface(fn=predict, # mapping function from input to output inputs=gr.inputs.Image(type='pil'), # What are the inputs? outputs=[gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs? gr.Number(label='Prediction time (s)')], # Our fn has two outputs, therefore we have two outputs examples=example_list, title=title, description=description, article=article )# Launch the demoprint('Gradio Demo Launched')demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344
import torchimport torch.nn as nnimport torchvision
# Create an EffNetB2 feature extractordef create_effnet_b2(num_of_class: str=3, transform: torchvision.transforms=None, seed=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. """ # 1. Get the base mdoel with pretrained weights and send to target device model = torchvision.models.efficientnet_b2(pretrained=True) # 2. Freeze the base model layers for param in model.parameters(): param.requires_grad = False # 3. Set the seeds torch.manual_seed(seed) # 4. Change the classifier head model.classifier = nn.Sequential(nn.Dropout(p=0.3, inplace=True), nn.Linear(1408, num_of_class, bias=True) ) return model, transform
# mymodel = create_effnet_b2(num_of_class=3, # transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor()]),# seed=42)# print(mymodel)1234
torch==1.10.0torchvision==0.11.0+cu102gradio==3.16.207_effnetb2_data_50_percent_10_epochs.pthAdded+3
09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pthAdded+3
app.pyAdded+91
examples/140016.jpgAdded

examples/647683.jpgAdded

examples/715227.jpgAdded

model.pyAdded+44
requirements.txtAdded+4