FloraFind / predict.py
crashn's picture
init app
9351b33 verified
Raw History Blame Contribute Delete
2.52 kB
"""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()