File size: 6,825 Bytes
3156eb6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
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}%") |