File size: 2,521 Bytes
9351b33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Predict the flower category of one photo and time the prediction.

Usage:
    python predict.py path/to/flower.jpg
"""
import argparse
import json
from pathlib import Path

import torch
from PIL import Image

from data_setup import TEST_TRANSFORM
from engine import predict_single_image
from model_builder import create_efficientnet_b0

PROJECT_DIR = Path(__file__).resolve().parent
MODEL_PATH = PROJECT_DIR / "models" / "flowers102_efficientnet_b0.pth"
CLASS_NAMES_PATH = PROJECT_DIR / "models" / "class_names.json"

# Single-image predictions run on the CPU, which avoids GPU transfer overhead and matches free web hosting.
DEVICE = "cpu"

# One CPU thread measured fastest for single EfficientNet-B0 predictions (about 0.06 s vs 0.25 s with 6 threads on an M1 Pro).
torch.set_num_threads(1)


def load_model(model_path=MODEL_PATH, class_names_path=CLASS_NAMES_PATH, device=DEVICE):
    class_names = json.loads(Path(class_names_path).read_text())
    model = create_efficientnet_b0(num_classes=len(class_names), pretrained=False)
    model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))
    model.to(device)
    model.eval()

    # Run one untimed pass so later timings exclude first-call setup.
    with torch.inference_mode():
        model(torch.zeros(1, 3, 224, 224, device=device))
    return model, class_names


def predict_image(model, class_names, image, device=DEVICE, top_k=5):
    # Return the top-k flower categories with their probabilities, plus the timed prediction.
    pred_probs, seconds = predict_single_image(model, image, TEST_TRANSFORM, device)
    top_probs, top_indices = pred_probs.topk(top_k)
    predictions = {
        class_names[index]: prob
        for prob, index in zip(top_probs.tolist(), top_indices.tolist())
    }
    return predictions, seconds


def main():
    parser = argparse.ArgumentParser(description="Predict the flower category of a photo.")
    parser.add_argument("image_path", help="path to a flower photo")
    parser.add_argument("--top-k", type=int, default=5, help="number of predictions to show")
    args = parser.parse_args()

    model, class_names = load_model()
    with Image.open(args.image_path) as image:
        predictions, seconds = predict_image(model, class_names, image, top_k=args.top_k)

    for rank, (class_name, prob) in enumerate(predictions.items(), start=1):
        print(f"{rank}. {class_name}: {prob:.2%}")
    print(f"Prediction time: {seconds:.4f} seconds")


if __name__ == "__main__":
    main()