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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
| import os import matplotlib.pyplot as plt import numpy as np import torch from torch import nn import torchvision import torch.optim as optim from torchvision import transforms,models,datasets import imageio import time import warnings import random import sys import copy import json from PIL import Image
data_dir = './flower_data/' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' num_classes = 102
data_transfroms = { 'train':transforms.Compose([ transforms.RandomRotation(45), transforms.CenterCrop(224), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomVerticalFlip(p=0.5), transforms.ColorJitter(brightness=0.2,contrast=0.1,saturation=0.1,hue=0.1), transforms.RandomGrayscale(p=0.025), transforms.ToTensor(),
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225]) ]), 'valid':transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225]) ]), }
batch_size = 8
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir,x),data_transfroms[x]) for x in ['train','valid']} dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x],batch_size=batch_size,shuffle=True) for x in ['train','valid']} dataset_sizes = {x: len(image_datasets[x]) for x in ['train','valid']} class_names = image_datasets['train'].classes print(class_names)
with open('cat_to_name.json','r') as f: cat_to_name = json.load(f) print(cat_to_name)
def im_convert(tensor): image = tensor.to("cpu").clone().detach() image = image.numpy().squeeze() image = image.transpose(1,2,0) image = image * np.array((0.229,0.224,0.225)) + np.array((0.485,0.456,0.406)) image = image.clip(0,1) return image
fig = plt.figure(figsize=(20,12))
columns = 4 rows = 2
dataiter = iter(dataloaders['train']) print(dataiter) inputs,classes = dataiter.next() print(classes)
for idx in range(columns * rows): ax = fig.add_subplot(rows, columns, idx+1, xticks=[], yticks=[]) ax.set_title(cat_to_name[str(int(class_names[classes[idx]]))]) plt.imshow(im_convert(inputs[idx]))
model_name = 'resnet'
feature_extract = True
train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('GPU false') else: print('GPU True')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def set_parameter_requires_grad(model, feature_extracting): if feature_extracting: for param in model.parameters(): param.requires_grad = False
model_ft = models.resnet152()
def initialize_model(model_name,num_classes,feature_extract,use_pretrained=True): model_ft = None input_size = 0
if model_name == 'resnet': model_ft = models.resnet152(pretrained=use_pretrained) set_parameter_requires_grad(model_ft,feature_extract) num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Sequential(nn.Linear(num_ftrs,num_classes),nn.LogSoftmax(dim=1)) input_size = 224
return model_ft, input_size
model_ft, input_size = initialize_model(model_name,num_classes,feature_extract,use_pretrained=True)
model_ft = model_ft.to(device)
filename = 'checkpoint.pth'
params_to_update = model_ft.parameters() print('Params to learn:')
if feature_extract: params_to_update = [] for name,param in model_ft.named_parameters(): if param.requires_grad == True: params_to_update.append(param) print("\t",name) else: for name,param in model_ft.named_parameters(): if param.requires_grad == True: print("\t",name)
optimizer_ft = optim.Adam(model_ft.parameters(),lr=1e-2) scheduler = optim.lr_scheduler.StepLR(optimizer_ft,step_size=7,gamma=0.1)
criterion = nn.NLLLoss()
def train_model(model, dataloaders, criterion, optimizer, num_epochs=10, is_inception=False, filename=filename): since = time.time() best_acc = 0
model.to(device)
val_acc_history = [] train_acc_history = [] train_losses = [] valid_losses = []
LRs = [optimizer.param_groups[0]['lr']] best_model_wts = copy.deepcopy(model.state_dict())
for epoch in range(num_epochs): print("Epoch {}/{}".format(epoch,num_epochs-1)) print('-'*10)
for phase in ['train','valid']: if phase == 'train': model.train() else: model.eval()
running_loss = 0.0 running_corrects = 0
for inputs,labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device)
optimizer.zero_grad() with torch.set_grad_enabled(phase == 'train'): if is_inception and phase == 'train': outputs, aux_outputs = model(inputs) loss1 = criterion(outputs,labels) loss2 = criterion(aux_outputs,labels) loss = loss1 + 0.4*loss2 else: outputs = model(inputs) loss = criterion(outputs,labels) _,preds = torch.max(outputs,1)
if phase == 'train': loss.backward() optimizer.step()
running_loss +=loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / len(dataloaders[phase].dataset) epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)
time_elapsed = time.time() - since print('Time elapsed {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
if phase == 'valid' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict())
state = { 'state_dict': model.state_dict(), 'best_acc': best_acc, 'optimizer': optimizer.state_dict(), } torch.save(state, filename) if phase == 'valid': val_acc_history.append(epoch_acc) valid_losses.append(epoch_loss) scheduler.step(epoch_loss) if phase == 'train': train_acc_history.append(epoch_acc) train_losses.append(epoch_loss)
print('Optimizer learning rate : {:.7f}'.format(optimizer.param_groups[0]['lr'])) LRs.append(optimizer.param_groups[0]['lr']) print()
time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('Best val Acc: {:4f}'.format(best_acc))
model.load_state_dict(best_model_wts) return model, val_acc_history, train_acc_history, valid_losses, train_losses, LRs
model_ft, val_acc_history, train_acc_history, valid_losses, train_losses, LRs = train_model(model_ft, dataloaders, criterion, optimizer_ft, num_epochs=10, is_inception=(model_name=="inception"))
|