Views
No views yet
pip install torch torchvision pillow1import torch
2import torchvision.models as models
3from huggingface_hub import hf_hub_download
4import json
5from PIL import Image
6import torchvision.transforms as transforms
7
8device = "cuda" if torch.cuda.is_available() else "cpu"
9
10weights_path = hf_hub_download(repo_id="AventIQ-AI/resnet18-sports-category-classification", filename="resnet18_sports_classification.pth")
11labels_path = hf_hub_download(repo_id="AventIQ-AI/resnet18-sports-category-classification", filename="class_labels.json")
12
13with open(labels_path, "r") as f:
14 class_labels = json.load(f)
15
16model = models.resnet18(pretrained=False)
17
18num_classes = len(class_labels)
19model.fc = torch.nn.Linear(in_features=512, out_features=num_classes)
20
21model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu')))
22
23model.eval()
24
25print("Model loaded successfully!")1def predict_image(image_path, model, class_names):
2 model.eval()
3
4 # Load and transform the image
5 transform = transforms.Compose([
6 transforms.Resize((224, 224)),
7 transforms.ToTensor(),
8 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
9 ])
10
11 image = Image.open(image_path).convert("RGB")
12 image_tensor = transform(image).unsqueeze(0).to(device) # Add batch dimension
13
14 # Predict
15 with torch.no_grad():
16 output = model(image_tensor)
17 _, predicted = torch.max(output, 1)
18
19 predicted_class = class_names[predicted.item()]
20 return predicted_class
21
22# Example usage:
23image_path = "image_path.jpg" # Change this to your image path
24predicted_sport = predict_image(image_path, model, class_labels)
25print(f"Predicted Sport Category: {predicted_sport}")| Metric | Score |
|---|---|
| Accuracy | 92.4% |
| Precision | 88.2% |
| Recall | 82.8% |
| F1-Score | 88.5% |