| 11 | model.eval() |
| 12 | |
| 13 | def resnext(input_image): |
| 14 | preprocess = Transforms.Compose([ |
| 15 | Transforms.Resize(256), |
| 16 | Transforms.CenterCrop(224), |
| 17 | Transforms.ToTensor(), |
| 18 | Transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), |
| 19 | ]) |
| 20 | input_tensor = preprocess(input_image) |
| 21 | input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model |
| 22 | |
| 23 | # move the input and model to GPU for speed if available |
| 24 | if torch.cuda.is_available(): |
| 25 | input_batch = input_batch.to('cuda') |
| 26 | model.to('cuda') |
| 27 | |
| 28 | with torch.no_grad(): |
| 29 | output = model(input_batch) |
| 30 | # Tensor of shape 1000, with confidence scores over Imagenet's 1000 classes |
| 31 | # print(output[0]) |
| 32 | # The output has unnormalized scores. To get probabilities, you can run a softmax on it. |
| 33 | probabilities = torch.nn.functional.softmax(output[0], dim=0) |
| 34 | # print(probabilities) |
| 35 | |
| 36 | # Show top categories per image |
| 37 | top5_prob, top5_catid = torch.topk(probabilities, 5) |
| 38 | |
| 39 | predictions = {} |
| 40 | for i in range(top5_prob.size(0)): |
| 41 | # print(categories[top5_catid[i]], top5_prob[i].item()) |
| 42 | predictions[categories[top5_catid[i]]] = top5_prob[i].item() |
| 43 | return predictions |