import torch from torchvision import transforms, models from data_loading import LMDBImageDataset from torch.utils.data import DataLoader from tqdm import tqdm import argparse torch.multiprocessing.set_sharing_strategy('file_system') def main(): # Parse command line arguments. parser = argparse.ArgumentParser(description="Compute ResNet embeddings") parser.add_argument('--resnet_type', type=str, default='resnet152', help="Type of ResNet model to use (e.g., resnet18, resnet34, resnet50, resnet101, resnet152)") parser.add_argument('--lmdb_path', type=str, default='../lmdb_all_crops_pmfeed_4_3_16', help="Path to the LMDB image dataset") args = parser.parse_args() transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), ]) # Create the dataset and dataloader. dataset = LMDBImageDataset( lmdb_path=args.lmdb_path, transform=transform, limit=None ) dataloader = DataLoader( dataset, batch_size=128, shuffle=False, num_workers=8, ) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Dynamically load the specified ResNet model. resnet_constructor = getattr(models, args.resnet_type) model = resnet_constructor(weights='IMAGENET1K_V1') # Remove the last fully-connected layer to obtain embeddings. model = list(model.children())[:-1] model = torch.nn.Sequential(*model) model.to(device) model.eval() all_embeddings = [] all_cow_ids = [] # Loop through the dataset and compute embeddings. with torch.no_grad(): for images, cow_ids in tqdm(dataloader, unit='batch'): images = images.to(device) image_features = model(images) image_features = image_features.squeeze() all_embeddings.append(image_features.cpu()) all_cow_ids.append(cow_ids) # Concatenate and save all embeddings. embeddings = torch.cat(all_embeddings, dim=0) torch.save(embeddings, f"{args.resnet_type}_embeddings.pt") all_cow_ids = torch.cat(all_cow_ids, dim=0) torch.save(all_cow_ids, f"all_cow_ids.pt") if __name__ == '__main__': main()