from torchvision.io import read_image from torchvision.models import resnet50, ResNet50_Weights import glob, os, csv import numpy as np from PIL import Image from torchvision import models, transforms import torch import torch.optim as optim import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import DataLoader, random_split device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) # Custom Dataset Class (Replace with your actual dataset class) class CustomDataset(torch.utils.data.Dataset): def __init__(self, root, transform=None): # Your dataset initialization code here self.transform = transform # read ui types in the csv file design_topics.csv dict_id_to_ui_type = {} with open('../enrico/design_topics.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') ui_types_set = set() for row in csv_reader: ui_types_set.add(row[1]) if row[1] == 'news': row[1] = 'gallery' dict_id_to_ui_type[row[0]] = row[1] ui_types_list = ['list', 'login', 'settings', 'menu', 'mediaplayer', 'form', 'profile', 'gallery']#list(ui_types_set) path = root folders = os.listdir(path) self.image_list = [] self.ui_type_list = [] c = 0 for f in folders: c += 1 if c % 50 == 0: print(c) image_path = path + f # image = read_image(image_path) # # resize to 1280 x 720 # image = image.resize((720, 1280)) # open image as numpy array # image = Image.open(image_path) # # resize the image to 1280 x 720 # image = image.resize((720, 1280)) # image.save(image_path) image = read_image(image_path).to(torch.uint8) self.image_list.append(image) # get the ui type of the image # image_name = '_'.join(f.split('_')[:2]) image_id = f.split('.')[0] ui_type = dict_id_to_ui_type[image_id] ui_type_index = ui_types_list.index(ui_type) label = torch.zeros(8).to(device) label[ui_type_index] = 1 self.ui_type_list.append(label) def __len__(self): # Return the number of samples in your dataset return len(self.image_list) def __getitem__(self, idx): # Load and return a sample from your dataset img = self.image_list[idx] if self.transform: img = self.transform(img) label = self.ui_type_list[idx] return img, label #img = read_image("./UI_images/enrico_124.jpg") # Step 1: Initialize model with the best available weights #weights = ResNet50_Weights.DEFAULT #model = resnet50(weights=weights) weights = ResNet50_Weights.DEFAULT resnet50 = models.resnet50(pretrained=True) #for param in resnet50.parameters(): # param.requires_grad = False num_ftrs = resnet50.fc.in_features resnet50.fc = nn.Linear(num_ftrs, 8) #num_features = model.fc.in_features #model = torch.nn.Sequential(*(list(model.children())[:-1])) #model.fc = nn.Linear(model.fc.in_features, 8) #layer = nn.Linear(num_features, 8) resnet50.to(device) #layer.to(device) #for n, p in model.named_parameters(): # p.require_grad = False #img = read_image("./UI_images/enrico_124.jpg") # Step 2: Initialize the inference transforms #preprocess = weights.transforms() transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) preprocess = weights.transforms() train_dataset = CustomDataset(root="./imgs/train/", transform=transforms.Compose([preprocess])) test_dataset = CustomDataset(root="./imgs/test/", transform=transforms.Compose([preprocess])) # Create data loaders train_loader = DataLoader(train_dataset, batch_size=256, shuffle=True) val_loader2 = DataLoader(test_dataset, batch_size=1, shuffle=False) # Define loss function and optimizer criterion = torch.nn.CrossEntropyLoss() criterion = torch.nn.BCEWithLogitsLoss() other_p = [] fc_p = [] for name, param in resnet50.named_parameters(): if not name.startswith('fc'): other_p.append(param) else: print(name) fc_p.append(param) params = [ {'params': fc_p, 'lr': 0.001}, {'params': other_p, 'lr': 0.0001} ] optimizer = optim.Adam(params, lr=0.001) #optimizer = optim.Adam(resnet50.parameters(), lr=0.0001) #optimizer = optim.Adam(resnet50.fc, lr=0.001) # Training loop num_epochs = 501 for epoch in range(num_epochs): print('epoch', epoch) resnet50.train() for inputs, labels in train_loader: inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = resnet50(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # compute the accuracy of each class # compute the accuracy of each class correct = 0 total = 0 with torch.no_grad(): if epoch != 0 and epoch % 5 == 0: # accuracy per class class_correct = list(0. for i in range(8)) class_total = list(0. for i in range(8)) with torch.no_grad(): for inputs, labels in val_loader2: inputs = inputs.to(device) labels = labels.to(device) outputs = resnet50(inputs) _, predicted = torch.max(outputs, 1) # c = (predicted == labels).squeeze() label_index = torch.where(labels[0] == 1)[0].item() label = int(label_index) c = (predicted == label).squeeze() class_correct[label] += c.item() class_total[label] += 1 correct += c.item() total += 1 print('Accuracy of the netxork on the test images: %.2f %%' % ( 100 * correct / total)) print(class_correct) print(class_total) for i in range(8): print('Accuracy of %5s : %.2f %%' % ( i, 100 * class_correct[i] / class_total[i])) # Step 4: Use the model and print the predicted category # prediction = model(128).squeeze(0).softmax(0) # class_id = prediction.argmax().item() # score = prediction[class_id].item() # category_name = weights.meta["categories"][class_id] # print(f"{category_name}: {100 * score:.1f}%")