Advertisement
lamiastella

fixed the leakage?

Nov 22nd, 2018
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.26 KB | None | 0 0
  1. Epoch 23/24
  2. ----------
  3. Loss: 0.1487 Acc: 0.9600
  4. Epoch 24/24
  5. ----------
  6. Loss: 0.1695 Acc: 0.9200
  7. Training complete in 1m 9s
  8. loocv preds:  [tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([1], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([1], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([0], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([0], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([0], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([1], device='cuda:0'), tensor([0], device='cuda:0'), tensor([1], device='cuda:0'), tensor([0], device='cuda:0')]
  9. loocv targets:  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
  10. 0.88
  11. [[23  2]
  12.  [ 4 21]]
  13. [jalal@goku official_tut]$ cat exp_loocv.py
  14. from __future__ import print_function, division
  15.  
  16. import torch
  17. from torch.autograd import Variable
  18. from sklearn.metrics import accuracy_score
  19. from sklearn.metrics import confusion_matrix
  20. import torch
  21. import torch.nn as nn
  22. import torch.optim as optim
  23. from torch.optim import lr_scheduler
  24. import numpy as np
  25. import torchvision
  26. from torchvision import datasets, models, transforms
  27. import matplotlib.pyplot as plt
  28. import time
  29. import os
  30. import copy
  31.  
  32.  
  33.  
  34. import torch.utils.data as data_utils
  35. from torch.utils import data
  36.  
  37.  
  38. data_transforms = {
  39.     'train': transforms.Compose([
  40.         transforms.RandomResizedCrop(224),
  41.         transforms.RandomHorizontalFlip(),
  42.         transforms.RandomRotation(20),
  43.         transforms.ColorJitter(.3, .3, .3),
  44.         transforms.ToTensor(),
  45.         transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  46.     ])
  47. }
  48.  
  49.  
  50. data_dir = "test_images"
  51.  
  52. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  53.  
  54.  
  55.  
  56. def train_model(model, criterion, optimizer, scheduler, dataloader, num_epochs=25):
  57.     since = time.time()
  58.  
  59.     for epoch in range(num_epochs):
  60.         print('Epoch {}/{}'.format(epoch, num_epochs - 1))
  61.         print('-' * 10)
  62.  
  63.         # Each epoch has a training and validation phase
  64.  
  65.         scheduler.step()
  66.         model.train()  # Set model to training mode
  67.  
  68.  
  69.         running_loss = 0.0
  70.         running_corrects = 0
  71.  
  72.         # Iterate over data.
  73.         for inputs, labels in dataloader:
  74.             inputs = inputs.to(device)
  75.             labels = labels.to(device)
  76.  
  77.             # zero the parameter gradients
  78.             optimizer.zero_grad()
  79.  
  80.             # forward
  81.             # track history if only in train
  82.             with torch.set_grad_enabled(True):
  83.                 outputs = model(inputs)
  84.                 _, preds = torch.max(outputs, 1)
  85.                 loss = criterion(outputs, labels)
  86.                 # backward + optimize only if in training phase
  87.                 loss.backward()
  88.                 optimizer.step()
  89.             # statistics
  90.             running_loss += loss.item() * inputs.size(0)
  91.             running_corrects += torch.sum(preds == labels.data)
  92.  
  93.         epoch_loss = running_loss / dataset_size['train']
  94.         epoch_acc = running_corrects.double() / dataset_size['train']
  95.  
  96.         print('Loss: {:.4f} Acc: {:.4f}'.format(epoch_loss, epoch_acc))
  97.  
  98.  
  99.  
  100.     time_elapsed = time.time() - since
  101.     print('Training complete in {:.0f}m {:.0f}s'.format(
  102.         time_elapsed // 60, time_elapsed % 60))
  103.  
  104.  
  105.  
  106.     return model
  107.  
  108.  
  109. ######################################################################
  110. # Finetuning the convnet
  111. # ----------------------
  112. #
  113. # Load a pretrained model and reset final fully connected layer.
  114. #
  115.  
  116. '''model_ft = models.resnet50(pretrained=True)
  117.  
  118. num_ftrs = model_ft.fc.in_features
  119. model_ft.fc = nn.Linear(num_ftrs, 2)
  120.  
  121. model_ft = model_ft.to(device)
  122.  
  123. criterion = nn.CrossEntropyLoss()
  124.  
  125. # Observe that all parameters are being optimized
  126. optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
  127.  
  128. # Decay LR by a factor of 0.1 every 7 epochs
  129. exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)'''
  130.  
  131.  
  132.  
  133. #model_ft = model_ft.cuda()
  134. nb_samples = 50
  135. nb_classes = 2
  136.  
  137.  
  138.  
  139. image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
  140.                                           data_transforms[x])
  141.                   for x in ['train']}
  142.  
  143. dataset_size = {x: len(image_datasets[x]) for x in ['train']}
  144. class_names = image_datasets['train'].classes
  145.  
  146. # LOOCV
  147. loocv_preds = []
  148. loocv_targets = []
  149. for idx in range(nb_samples):
  150.  
  151.     print('Using sample {} as test data'.format(idx))
  152.  
  153.     # Get all indices and remove test sample
  154.     train_indices = list(range(len(image_datasets['train'])))
  155.     del train_indices[idx]
  156.  
  157.     # Create new sampler
  158.     sampler = data.SubsetRandomSampler(train_indices)
  159.     print('sampler size: ', len(sampler))
  160.  
  161.     dataloader = data.DataLoader(
  162.         image_datasets['train'],
  163.         num_workers=2,
  164.         batch_size=1,
  165.         sampler=sampler
  166.     )
  167.  
  168.     # Train model
  169.     #for batch_idx, (sample, target) in enumerate(dataloader):
  170.     #print('Batch {}'.format(batch_idx))
  171.     model_ft = models.resnet50(pretrained=True)
  172.  
  173.     num_ftrs = model_ft.fc.in_features
  174.     model_ft.fc = nn.Linear(num_ftrs, 2)
  175.  
  176.     model_ft = model_ft.to(device)
  177.  
  178.     criterion = nn.CrossEntropyLoss()
  179.  
  180.     # Observe that all parameters are being optimized
  181.     optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
  182.  
  183.     # Decay LR by a factor of 0.1 every 7 epochs
  184.     exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
  185.     model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, dataloader, num_epochs=25) # do I add this line here?
  186.  
  187.     # Test on LOO sample
  188.     model_ft.eval()
  189.     test_data, test_target = image_datasets['train'][idx]
  190.     test_data = test_data.cuda()
  191.     test_target = torch.tensor(test_target)
  192.     test_target = test_target.cuda()
  193.     test_data.unsqueeze_(0)
  194.     test_target.unsqueeze_(0)
  195.     output = model_ft(test_data)
  196.     pred = torch.argmax(output, 1)
  197.     loocv_preds.append(pred)
  198.     loocv_targets.append(test_target.item())
  199.  
  200.  
  201. print("loocv preds: ", loocv_preds)
  202. print("loocv targets: ", loocv_targets)
  203. print(accuracy_score(loocv_targets, loocv_preds))
  204. print(confusion_matrix(loocv_targets, loocv_preds))
  205.  
  206. [jalal@goku official_tut]$
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement