|
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) |
|
|
|
|
|
class CustomDataset(torch.utils.data.Dataset): |
|
def __init__(self, root, transform=None): |
|
|
|
|
|
self.transform = transform |
|
|
|
|
|
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'] |
|
|
|
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).to(torch.uint8) |
|
|
|
self.image_list.append(image) |
|
|
|
|
|
|
|
|
|
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 len(self.image_list) |
|
|
|
def __getitem__(self, idx): |
|
|
|
img = self.image_list[idx] |
|
|
|
if self.transform: |
|
img = self.transform(img) |
|
|
|
label = self.ui_type_list[idx] |
|
return img, label |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
weights = ResNet50_Weights.DEFAULT |
|
resnet50 = models.resnet50(pretrained=True) |
|
|
|
|
|
|
|
num_ftrs = resnet50.fc.in_features |
|
resnet50.fc = nn.Linear(num_ftrs, 8) |
|
|
|
|
|
|
|
|
|
resnet50.to(device) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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])) |
|
|
|
|
|
train_loader = DataLoader(train_dataset, batch_size=256, shuffle=True) |
|
val_loader2 = DataLoader(test_dataset, batch_size=1, shuffle=False) |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
|
correct = 0 |
|
total = 0 |
|
with torch.no_grad(): |
|
if epoch != 0 and epoch % 5 == 0: |
|
|
|
|
|
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) |
|
|
|
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])) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|