outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() # Running loss update running_loss += loss.item() # Print the running loss every 1000 mini-batches if i % 1000 == 999: print('Epoch : %2d, mini-batch : %4d, loss : %.3f' % (epoch, i + 1, running_loss / 1000)) running_loss = 0.0 # Set the model to evaluation mode model.eval() # Compute training set accuracy training_correct = 0 training_total = 0 with torch.no_grad(): for data in trainloader: images, labels = data outputs = model(images) predicted = torch.argmax(outputs.data, 1) training_correct += (predicted == labels).sum().item() training_total += labels.size(0) training_accuracy = 100. * training_correct / training_total # Compute test set accuracy test_correct = 0
def main(args): #hyper parameter end_epoch = 200 lr = 0.001 beta1 = 0.5 beta2 = 0.99 gpu = 0 #set model model = MyNet() #set GPU or CPU if gpu >= 0 and torch.cuda.is_available(): device = 'cuda:{}'.format(gpu) else: device = 'cpu' model.to(device) model.load_state_dict( torch.load("models/" + args.model + "/" + str(args.epoch - 1) + ".pth")) model.eval() criteria = nn.CrossEntropyLoss() dataset = MyDataset("data/", is_train=False) test_loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True) with torch.no_grad(): epoch_loss = 0 epoch_acc = 0 if not os.path.exists("result/" + args.model + "/true_favo/"): os.makedirs("result/" + args.model + "/true_favo/") os.makedirs("result/" + args.model + "/true_no_favo/") os.makedirs("result/" + args.model + "/false_favo/") os.makedirs("result/" + args.model + "/false_no_favo/") for i, data in enumerate(test_loader): print("\riteration: {}".format(i), end="") inputs, labels = data outputs = model(inputs.to(device)) _, preds = torch.max(outputs.data, 1) loss = criteria(outputs, labels.to(device)) favo_preds = preds.to('cpu') if favo_preds == labels: if favo_preds == 1: save_image( inputs, "result/" + args.model + "/true_favo/" + str(i) + ".jpg") elif favo_preds == 0: save_image( inputs, "result/" + args.model + "/true_no_favo/" + str(i) + ".jpg") else: if favo_preds == 1: save_image( inputs, "result/" + args.model + "/false_favo/" + str(i) + ".jpg") elif favo_preds == 0: save_image( inputs, "result/" + args.model + "/false_no_favo/" + str(i) + ".jpg") epoch_loss += loss.data.to('cpu') * inputs.size(0) epoch_acc += torch.sum(favo_preds == labels.data) epoch_loss /= len(test_loader) epoch_acc = epoch_acc / float(len(test_loader)) print("[Loss: {}] [Acc: {}]".format(epoch_loss, epoch_acc))