Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.02 KB | None | 0 0
  1. # First, we extend the VGG16 model with our new classifier
  2. e2e_model = models.vgg16(pretrained=True)
  3. e2e_model.train()
  4.  
  5. classifier = list(e2e_model.classifier.children())[:-1]
  6. classifier.append(torch.nn.Linear(4096, 512))
  7. classifier.append(torch.nn.Sigmoid())
  8. classifier.append(torch.nn.Linear(512, 80))
  9. # Second sigmoid layer is dropped as it's included in the loss calculation
  10. e2e_model.classifier = nn.Sequential(*classifier)
  11.  
  12. # The output data is prepared by representing each output as a binary vector of categories
  13. class TrainData(Dataset):
  14. __xs = []
  15. __ys = []
  16.  
  17. def __init__(self):
  18. for train_id in train_ids:
  19. # Create the 80 dimensional vector label
  20. y_vector = np.zeros(80)
  21. for category in train_id_to_categories[train_id]:
  22. idx = category_to_idx[category]
  23. y_vector[idx] = 1
  24.  
  25. self.__xs.append(train_id)
  26. self.__ys.append(y_vector)
  27.  
  28. def __getitem__(self, index):
  29. image_id = self.__xs[index]
  30. labels = self.__ys[index]
  31.  
  32. # Load and return tensor representation of image with labels
  33. image = Image.open(train_id_to_file[image_id]).convert('RGB')
  34. image_tensor = loader(image).float()
  35. return image_tensor, labels
  36.  
  37. def __len__(self):
  38. return len(self.__xs)
  39.  
  40. def train(model, learning_rate=0.0001, batch_size=50, epochs=1):
  41. """
  42. Training function which takes as input a model, a learning rate and a batch size.
  43.  
  44. After completing a full pass over the data, the function exists, and the input model will be trained.
  45. """
  46. train_data = TrainData()
  47. train_loader = torch.utils.data.DataLoader(dataset=train_data,
  48. batch_size=batch_size,
  49. shuffle=True)
  50. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
  51. model.train()
  52.  
  53.  
  54. for epoch in range(epochs):
  55. for batch_idx, (data, target) in enumerate(train_loader):
  56. # Get the inputs
  57. target = target.type(torch.FloatTensor)
  58. data, target = data.cuda(), target.cuda()
  59. data, target = Variable(data), Variable(target)
  60.  
  61. # Zero the parameter gradients
  62. optimizer.zero_grad()
  63.  
  64. # Forward + Backward + Optimize
  65. output = model(data)
  66. loss = F.multilabel_soft_margin_loss(output, target)
  67. loss.backward()
  68. optimizer.step()
  69.  
  70. # Print statistics
  71. if batch_idx % 25 == 0:
  72. print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
  73. epoch+1, batch_idx * len(data), len(train_loader.dataset),
  74. 100. * batch_idx / len(train_loader), loss.data[0]))
  75.  
  76.  
  77. # Finally train the model
  78. start = time.time()
  79. train(e2e_model.cuda())
  80.  
  81. # Print elapsed time in seconds
  82. end = time.time()
  83. print(str(end - start) + " seconds elapsed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement