前提・実現したいこと
Python初心者です。
Resnet18画像分類の訓練済みモデルを用いて人の顔を見分けるためのファインチューニングを実施しようとしています。Pytorchの公式チュートリアルを参考にコードを書きました。学習はされますが学習済みモデル(arashi.pth)が保存されず"tkinter.TclError"になってしまいます。
間違っている箇所があれば指摘していただけると幸いです。
用意されているデータセットで行った際は問題なく実装できました。
発生している問題・エラーメッセージ
Traceback (most recent call last): File "Finetuning/5_10.py", line 133, in <module> imshow(out, title=[class_names[x] for x in classes]) File "Finetuning/5_10.py", line 27, in imshow plt.pause(10) # pause a bit so that plots are updated File "/home/selen/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/pyplot.py", line 313, in pause canvas.start_event_loop(interval) File "/home/selen/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/backend_bases.py", line 2288, in start_event_loop self.flush_events() File "/home/selen/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/backends/_backend_tk.py", line 405, in flush_events self._master.update() File "/home/selen/.pyenv/versions/3.7.3/lib/python3.7/tkinter/__init__.py", line 1177, in update self.tk.call('update') _tkinter.TclError: can't invoke "update" command: application has been destroyed
該当のソースコード
Python
1from __future__ import print_function, division 2 3import torch 4import torch.nn as nn 5import torch.optim as optim 6from torch.optim import lr_scheduler 7import numpy as np 8import torchvision 9from torchvision import datasets, models, transforms 10import matplotlib.pyplot as plt 11import time 12import os 13import copy 14 15plt.ion() # interactive mode 16 17def imshow(inp, title=None): 18 """Imshow for Tensor.""" 19 inp = inp.numpy().transpose((1, 2, 0)) 20 mean = np.array([0.485, 0.456, 0.406]) 21 std = np.array([0.229, 0.224, 0.225]) 22 inp = std * inp + mean 23 inp = np.clip(inp, 0, 1) 24 plt.imshow(inp) 25 if title is not None: 26 plt.title(title) 27 plt.pause(10) # pause a bit so that plots are updated 28 29def train_model(model, criterion, optimizer, scheduler, num_epochs=25): 30 since = time.time() 31 32 best_model_wts = copy.deepcopy(model.state_dict()) 33 best_acc = 0.0 34 35 for epoch in range(num_epochs): 36 print('Epoch {}/{}'.format(epoch, num_epochs - 1)) 37 print('-' * 10) 38 39 # Each epoch has a training and validation phase 40 for phase in ['train', 'val']: 41 if phase == 'train': 42 model.train() # Set model to training mode 43 else: 44 model.eval() # Set model to evaluate mode 45 46 running_loss = 0.0 47 running_corrects = 0 48 49 # Iterate over data. 50 for inputs, labels in dataloaders[phase]: 51 inputs = inputs.to(device) 52 labels = labels.to(device) 53 54 # zero the parameter gradients 55 optimizer.zero_grad() 56 57 # forward 58 # track history if only in train 59 with torch.set_grad_enabled(phase == 'train'): 60 outputs = model(inputs) 61 _, preds = torch.max(outputs, 1) 62 loss = criterion(outputs, labels) 63 64 # backward + optimize only if in training phase 65 if phase == 'train': 66 loss.backward() 67 optimizer.step() 68 69 # statistics 70 running_loss += loss.item() * inputs.size(0) 71 running_corrects += torch.sum(preds == labels.data) 72 if phase == 'train': 73 scheduler.step() 74 75 epoch_loss = running_loss / dataset_sizes[phase] 76 epoch_acc = running_corrects.double() / dataset_sizes[phase] 77 78 print('{} Loss: {:.4f} Acc: {:.4f}'.format( 79 phase, epoch_loss, epoch_acc)) 80 81 # deep copy the model 82 if phase == 'val' and epoch_acc > best_acc: 83 best_acc = epoch_acc 84 best_model_wts = copy.deepcopy(model.state_dict()) 85 86 print() 87 88 time_elapsed = time.time() - since 89 print('Training complete in {:.0f}m {:.0f}s'.format( 90 time_elapsed // 60, time_elapsed % 60)) 91 print('Best val Acc: {:4f}'.format(best_acc)) 92 93 # load best model weights 94 model.load_state_dict(best_model_wts) 95 return model 96 97data_transforms = { 98 'train': transforms.Compose([ 99 transforms.RandomResizedCrop(224), 100 transforms.RandomHorizontalFlip(), 101 transforms.ToTensor(), 102 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) 103 ]), 104 'val': transforms.Compose([ 105 transforms.Resize(256), 106 transforms.CenterCrop(224), 107 transforms.ToTensor(), 108 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) 109 ]), 110} 111 112data_dir = '/home/selen/downloads' 113image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), 114 data_transforms[x]) 115 for x in ['train', 'val']} 116dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4, 117 shuffle=True, num_workers=4) 118 for x in ['train', 'val']} 119dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']} 120class_names = image_datasets['train'].classes 121 122device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") 123 124 125 126 127# Get a batch of training data 128inputs, classes = next(iter(dataloaders['train'])) 129 130# Make a grid from batch 131out = torchvision.utils.make_grid(inputs) 132 133imshow(out, title=[class_names[x] for x in classes]) 134 135model_ft = models.resnet18(pretrained=True) 136num_ftrs = model_ft.fc.in_features 137# Here the size of each output sample is set to 2. 138# Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)). 139model_ft.fc = nn.Linear(num_ftrs, 2) 140 141model_ft = model_ft.to(device) 142 143criterion = nn.CrossEntropyLoss() 144 145# Observe that all parameters are being optimized 146optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9) 147 148# Decay LR by a factor of 0.1 every 7 epochs 149exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1) 150 151model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, 152 num_epochs=25) 153#学習済みデータ保存 154PATH = './arashi.pth' 155torch.save(model_ft.state_dict(), PATH)
回答1件
あなたの回答
tips
プレビュー