Lautaro Suarez commited on
Commit ·
4479560
1
Parent(s): 5b19461
Track large model files with Git LFS
Browse filesFiles changed (5)
- README.mdAdded+31
- argentinian_id_validation.pyAdded+122
- dni_image_validation_model_v0.pthAdded+3
- requirements.txtAdded+3
- test_model.pyAdded+56
12345678910111213141516171819202122232425262728293031# Argentinian ID Validation Model
This model was trained to validate Argentinian IDs based on images of the front, back, and invalid IDs. The model uses a ResNet18 architecture and classifies images into three categories: `valid_front`, `valid_back`, and `invalid`.
## Usage
- The model can be loaded in PyTorch using the `.pth` file or in ONNX format for deployment in a variety of environments.- You can test the model with the `test_model.py` script.
## Files
- `argentinian_id_validation.py`: Code used for training the model.- `test_model.py`: Script to test the model on new data.- `dni_image_validation_model.pth`: PyTorch model weights.- `dni_image_validation_model.onnx`: ONNX version of the model.
## Conversion to ONNX
To convert the PyTorch model to ONNX, the following code was used:```pythonimport torchimport torchvision.models as models
model = models.resnet18(pretrained=False)model.fc = torch.nn.Linear(model.fc.in_features, 3) # 3 classesmodel.load_state_dict(torch.load('dni_image_validation_model.pth'))
dummy_input = torch.randn(1, 3, 224, 224) # Input shapetorch.onnx.export(model, dummy_input, "dni_image_validation_model.onnx", input_names=['input'], output_names=['output'], opset_version=11)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import torchimport torch.nn as nnimport torch.optim as optimfrom torchvision import datasets, models, transformsfrom torch.utils.data import DataLoaderimport osimport certifiimport sslssl._create_default_https_context = ssl.create_default_contextprint(certifi.where())
# Define transforms for training and testing datasets# data_transforms = {# 'train': transforms.Compose([# transforms.Resize((224, 224)),# transforms.RandomHorizontalFlip(),# transforms.ToTensor(),# transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])# ]),# # 'val': transforms.Compose([# # transforms.Resize((224, 224)),# # transforms.ToTensor(),# # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])# # ]),# }data_transforms = { 'train': transforms.Compose([ transforms.Resize((224, 224)), transforms.RandomHorizontalFlip(), transforms.RandomRotation(30), transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1), transforms.RandomResizedCrop(224, scale=(0.8, 1.0)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]),}
# Load datasets (train/val directories should have valid_front, valid_back, invalid)data_dir = './data_dir'
# Check if paths are correctprint(f"Data directory: {os.path.abspath(data_dir)}")for folder in ['invalid', 'valid_front', 'valid_back']: folder_path = os.path.join(data_dir, folder) if os.path.exists(folder_path): print(f"Folder {folder} exists at {folder_path}") else: print(f"Folder {folder} does NOT exist!")
# image_datasets = {x: datasets.ImageFolder(f'{data_dir}/{x}', data_transforms[x]) for x in ['train']}# dataloaders = {x: DataLoader(image_datasets[x], batch_size=32, shuffle=True, num_workers=0) for x in ['train']}# image_datasets = {# 'train': datasets.ImageFolder(data_dir, data_transforms['train'])# }
# The DataLoader remains the same# dataloaders = {# 'train': DataLoader(image_datasets['train'], batch_size=32, shuffle=True, num_workers=0)# }
image_datasets = {x: datasets.ImageFolder(f'{data_dir}/{x}', data_transforms[x]) for x in ['train']}dataloaders = {x: DataLoader(image_datasets[x], batch_size=32, shuffle=True, num_workers=0) for x in ['train']}print(image_datasets['train'].class_to_idx, "check the class_to_idx")
# Use a pre-trained ResNet modelmodel = models.resnet18(pretrained=True)
# Modify the final layer to classify three classes (valid_front, valid_back, invalid)num_ftrs = model.fc.in_featuresmodel.fc = nn.Linear(num_ftrs, 3) # Output size is 3
# Move the model to the GPU if availabledevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")model = model.to(device)
# Define loss function and optimizercriterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=0.001)
# Training loopnum_epochs = 10for epoch in range(num_epochs): print(f'Epoch {epoch+1}/{num_epochs}') print('-' * 10)
for phase in ['train']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode
running_loss = 0.0 running_corrects = 0
for inputs, labels in dataloaders[phase]: inputs, labels = inputs.to(device), labels.to(device)
# Zero the parameter gradients optimizer.zero_grad()
# Forward pass with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels)
# Backward pass + optimization if in training phase if phase == 'train': loss.backward() optimizer.step()
# Statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / len(image_datasets[phase]) epoch_acc = running_corrects.double() / len(image_datasets[phase])
print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# Save the trained modeltorch.save(model.state_dict(), 'dni_image_validation_modelv3.pth')123version https://git-lfs.github.com/spec/v1oid sha256:0935cf6eb2c5295de01167be73962a24730f939e3d3f46dbf708742306a53a23size 44792020123torchscikit-learnnumpy1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import torchimport torch.nn as nnfrom torchvision import models, transformsfrom torch.autograd import Variablefrom PIL import Imageimport os
# Define the devicedevice = 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_featuresmodel.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 trainingtransform = 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 imagedef 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 imagedef 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 imageif __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}')README.mdAdded+31
argentinian_id_validation.pyAdded+122
dni_image_validation_model_v0.pthAdded+3
requirements.txtAdded+3
test_model.pyAdded+56