核心语句:

    1. from datetime import datetime
    2. prev_time = datetime.now()
    3. ...
    4. cur_time = datetime.now()
    5. h, remainder = divmod((cur_time - prev_time).seconds, 3600) #divmod的返回值:商和余数
    6. m, s = divmod(remainder, 60)
    7. time_str = "Time %02d:%02d:%02d" % (h, m, s)

    参考下面实例

    1. def train(net, train_data, valid_data, num_epochs, optimizer, criterion):
    2. prev_time = datetime.now()
    3. for epoch in range(num_epochs):
    4. train_loss = 0
    5. train_acc = 0
    6. net = net.train()
    7. for im, label in train_data:
    8. im = im.to(device) # (bs, 3, h, w)
    9. label = label.to(device) # (bs, h, w)
    10. # forward
    11. output = net(im)
    12. loss = criterion(output, label)
    13. # backward
    14. optimizer.zero_grad()
    15. loss.backward()
    16. optimizer.step()
    17. train_loss += loss.item()
    18. train_acc += get_acc(output, label)
    19. writer.add_scalar('训练损失值', train_loss, epoch) #记录损失值准备可视化
    20. cur_time = datetime.now()
    21. h, remainder = divmod((cur_time - prev_time).seconds, 3600)
    22. m, s = divmod(remainder, 60)
    23. time_str = "Time %02d:%02d:%02d" % (h, m, s)
    24. if valid_data is not None:
    25. valid_loss = 0
    26. valid_acc = 0
    27. net = net.eval()
    28. for im, label in valid_data:
    29. im = im.to(device) # (bs, 3, h, w)
    30. label = label.to(device) # (bs, h, w)
    31. output = net(im)
    32. loss = criterion(output, label)
    33. valid_loss += loss.item()
    34. valid_acc += get_acc(output, label)
    35. epoch_str = (
    36. "Epoch %d. Train Loss: %f, Train Acc: %f, Valid Loss: %f, Valid Acc: %f, "
    37. % (epoch, train_loss / len(train_data),
    38. train_acc / len(train_data), valid_loss / len(valid_data),
    39. valid_acc / len(valid_data)))
    40. else:
    41. epoch_str = ("Epoch %d. Train Loss: %f, Train Acc: %f, " %
    42. (epoch, train_loss / len(train_data),
    43. train_acc / len(train_data)))
    44. prev_time = cur_time
    45. print(epoch_str + time_str)