Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Image prediction using trained model #2392

Merged
merged 17 commits into from
Jun 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions beginner_source/transfer_learning_tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import matplotlib.pyplot as plt
import time
import os
from PIL import Image
from tempfile import TemporaryDirectory

cudnn.benchmark = True
Expand Down Expand Up @@ -337,6 +338,47 @@ def visualize_model(model, num_images=6):
plt.ioff()
plt.show()


######################################################################
# Inference on custom images
# --------------------------
#
# Use the trained model to make predictions on custom images and visualize
# the predicted class labels along with the images.
#

def visualize_model_predictions(model,img_path):
was_training = model.training
model.eval()

img = Image.open(img_path)
img = data_transforms['val'](img)
img = img.unsqueeze(0)
img = img.to(device)

with torch.no_grad():
outputs = model(img)
_, preds = torch.max(outputs, 1)

ax = plt.subplot(2,2,1)
ax.axis('off')
ax.set_title(f'Predicted: {class_names[preds[0]]}')
imshow(img.cpu().data[0])

model.train(mode=was_training)

######################################################################
#

visualize_model_predictions(
model_conv,
img_path='data/hymenoptera_data/val/bees/72100438_73de9f17af.jpg'
)

plt.ioff()
plt.show()


######################################################################
# Further Learning
# -----------------
Expand Down