train.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import copy
  2. import time
  3. from typing import List, Tuple, Optional
  4. import torch
  5. import torch.optim as optim
  6. from torch import nn
  7. from data import AudioVideo
  8. from kissing_detector import KissingDetector
  9. def _get_params_to_update(model: nn.Module,
  10. feature_extract: bool) -> List[nn.parameter.Parameter]:
  11. params_to_update = model.parameters()
  12. if feature_extract:
  13. print('Params to update')
  14. params_to_update = []
  15. for name, param in model.named_parameters():
  16. if param.requires_grad is True:
  17. params_to_update.append(param)
  18. print("*", name)
  19. else:
  20. print('Updating ALL params')
  21. return params_to_update
  22. def train_kd(data_path_base: str,
  23. conv_model_name: Optional[str],
  24. num_epochs: int,
  25. feature_extract: bool,
  26. batch_size: int,
  27. num_workers: int = 4,
  28. shuffle: bool = True,
  29. lr: float = 0.001,
  30. momentum: float = 0.9) -> Tuple[nn.Module, List[float], List[float]]:
  31. num_classes = 2
  32. kd = KissingDetector(conv_model_name, num_classes, feature_extract)
  33. params_to_update = _get_params_to_update(kd, feature_extract)
  34. datasets = {set_: AudioVideo(f'{data_path_base}/{set_}') for set_ in ['train', 'val']}
  35. dataloaders_dict = {x: torch.utils.data.DataLoader(datasets[x],
  36. batch_size=batch_size,
  37. shuffle=shuffle, num_workers=num_workers)
  38. for x in ['train', 'val']}
  39. optimizer_ft = optim.SGD(params_to_update, lr=lr, momentum=momentum)
  40. # Setup the loss fxn
  41. criterion = nn.CrossEntropyLoss()
  42. return train_model(kd,
  43. dataloaders_dict, criterion, optimizer_ft, num_epochs=num_epochs,
  44. is_inception=(conv_model_name == "inception"))
  45. def train_model(model, dataloaders, criterion, optimizer, num_epochs=25, is_inception=False):
  46. since = time.time()
  47. val_acc_history = []
  48. val_f1_history = []
  49. best_model_wts = copy.deepcopy(model.state_dict())
  50. best_acc = 0.0
  51. best_f1 = 0.0
  52. # Detect if we have a GPU available
  53. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  54. for epoch in range(num_epochs):
  55. print('Epoch {}/{}'.format(epoch, num_epochs - 1))
  56. print('-' * 10)
  57. # Each epoch has a training and validation phase
  58. for phase in ['train', 'val']:
  59. if phase == 'train':
  60. model.train() # Set model to training mode
  61. else:
  62. model.eval() # Set model to evaluate mode
  63. running_loss = 0.0
  64. running_corrects = 0
  65. running_tp = 0
  66. running_fp = 0
  67. running_fn = 0
  68. # Iterate over data.
  69. for a, v, labels in dataloaders[phase]:
  70. a = a.to(device)
  71. v = v.to(device)
  72. labels = labels.to(device)
  73. # zero the parameter gradients
  74. optimizer.zero_grad()
  75. # forward
  76. # track history if only in train
  77. with torch.set_grad_enabled(phase == 'train'):
  78. # Get model outputs and calculate loss
  79. # Special case for inception because in training it has an auxiliary output. In train
  80. # mode we calculate the loss by summing the final output and the auxiliary output
  81. # but in testing we only consider the final output.
  82. if is_inception and phase == 'train':
  83. # https://discuss.pytorch.org/t/how-to-optimize-inception-model-with-auxiliary-classifiers/7958
  84. outputs, aux_outputs = model(a, v)
  85. loss1 = criterion(outputs, labels)
  86. loss2 = criterion(aux_outputs, labels)
  87. loss = loss1 + 0.4 * loss2
  88. else:
  89. outputs = model(a, v)
  90. loss = criterion(outputs, labels)
  91. _, preds = torch.max(outputs, 1)
  92. # backward + optimize only if in training phase
  93. if phase == 'train':
  94. loss.backward()
  95. optimizer.step()
  96. # statistics
  97. running_loss += loss.item() * a.size(0)
  98. running_corrects += torch.sum(preds == labels.data)
  99. running_tp += torch.sum((preds == labels.data)[labels.data == 1])
  100. running_fp += torch.sum((preds != labels.data)[labels.data == 1])
  101. running_fn += torch.sum((preds != labels.data)[labels.data == 0])
  102. epoch_loss = running_loss / len(dataloaders[phase].dataset)
  103. n = len(dataloaders[phase].dataset)
  104. epoch_acc = running_corrects.double() / n
  105. tp = running_tp.double()
  106. fp = running_fp.double()
  107. fn = running_fn.double()
  108. p = tp / (tp + fp)
  109. r = tp / (tp + fn)
  110. epoch_f1 = 2 * p * r / (p + r)
  111. print('{} Loss: {:.4f} F1: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_f1, epoch_acc))
  112. # deep copy the model
  113. if phase == 'val' and epoch_acc > best_acc:
  114. best_acc = epoch_acc
  115. if phase == 'val' and epoch_f1 > best_f1:
  116. best_f1 = epoch_f1
  117. best_model_wts = copy.deepcopy(model.state_dict())
  118. if phase == 'val':
  119. val_acc_history.append(float(epoch_acc))
  120. val_f1_history.append(float(epoch_f1))
  121. print()
  122. time_elapsed = time.time() - since
  123. print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
  124. print('Best val F1 : {:4f}'.format(best_f1))
  125. print('Best val Acc : {:4f}'.format(best_acc))
  126. # load best model weights
  127. model.load_state_dict(best_model_wts)
  128. return model, val_acc_history, val_f1_history