Download test_model.py from Lautarosuarez/argentinian_ids: direct link, hf CLI and curl.
- Browser
- Download file 2.03 kB
-
https://huggingface.co/Lautarosuarez/argentinian_ids/resolve/main/test_model.py
- Command line
-
hf download hf://Lautarosuarez/argentinian_ids/test_model.py
-
curl -L -o test_model.py https://huggingface.co/Lautarosuarez/argentinian_ids/resolve/main/test_model.py
2.03 kB
| import torch | |
| import torch.nn as nn | |
| from torchvision import models, transforms | |
| from torch.autograd import Variable | |
| from PIL import Image | |
| import os | |
| # Define the device | |
| device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") | |
| # Load the trained model (Assumes 'dni_image_validation_model.pth' is in the same folder as this script) | |
| model = models.resnet18(weights=None) | |
| num_ftrs = model.fc.in_features | |
| model.fc = nn.Linear(num_ftrs, 3) # Assuming two classes: valid and invalid | |
| # model.load_state_dict(torch.load('./dni_image_validation_model.pth', map_location=device)) | |
| model.load_state_dict(torch.load('./dni_image_validation_modelv3.pth', map_location=device)) | |
| model = model.to(device) | |
| model.eval() # Set the model to evaluation mode | |
| # Define the same image transformations used during training | |
| transform = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) | |
| ]) | |
| # Function to load and process the image | |
| def process_image(image_path): | |
| image = Image.open(image_path) | |
| image = transform(image).unsqueeze(0) # Add batch dimension | |
| return image | |
| # Function to predict the class of an image | |
| def predict_image(image_path): | |
| image = process_image(image_path).to(device) | |
| # Forward pass through the model | |
| with torch.no_grad(): | |
| outputs = model(image) | |
| _, predicted = torch.max(outputs, 1) | |
| # Prediction output | |
| classes = ['invalid', 'valid_back', 'valid_front'] | |
| prediction = classes[predicted.item()] | |
| print(f'Prediction for {os.path.basename(image_path)}: {prediction}') | |
| # Test the model with a new image | |
| if __name__ == '__main__': | |
| # Path to the test image (Ensure you provide the correct image file name) | |
| test_image_path = './data_dir/tests/test01.jpeg' # Replace with your actual test image file | |
| if os.path.exists(test_image_path): | |
| predict_image(test_image_path) | |
| else: | |
| print(f'Image not found: {test_image_path}') | |