Views
No views yet
1import torch
2import torch.nn as nn
3from torchvision import models, transforms
4from PIL import Image
5import numpy as np
6
7# Define model architecture
8model = models.resnet50(pretrained=False)
9num_ftrs = model.fc.in_features
10model.fc = nn.Sequential(
11 nn.Dropout(0.5),
12 nn.Linear(num_ftrs, 512),
13 nn.ReLU(),
14 nn.Dropout(0.3),
15 nn.Linear(512, 2)
16)
17
18# Load weights
19device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
20checkpoint = torch.load('agglutinine_presence.pth', map_location=device)
21model.load_state_dict(checkpoint['model_state_dict'] if 'model_state_dict' in checkpoint else checkpoint)
22model.to(device)
23model.eval()
24
25# Define preprocessing
26transform = transforms.Compose([
27 transforms.Resize((600, 800)),
28 transforms.ToTensor(),
29 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
30])
31
32# Load and preprocess image
33image = Image.open("path/to/image.jpg").convert('RGB')
34image_tensor = transform(image).unsqueeze(0).to(device)
35
36# Inference
37with torch.no_grad():
38 outputs = model(image_tensor)
39 probabilities = torch.softmax(outputs, dim=1)
40 predicted_class = torch.argmax(probabilities, dim=1).item()
41 confidence = probabilities[0][predicted_class].item()
42
43class_names = ["Negative", "Positive"]
44print(f"Prediction: {class_names[predicted_class]}")
45print(f"Confidence: {confidence:.4f}")
46print(f"Positive probability: {probabilities[0][1].item():.4f}")@misc{sperm-agglutinine-detector,
author = {Raid Athmane Benlala},
title = {Sperm Agglutinine Presence Detector},
year = {2025},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/raidAthmaneBenlala/agglutinine-detector}}
}