训练模型时,导入 tensorboard. SummaryWriter 保存 loss、accuracy 等日志信息。
code
# 导入SummaryWriter
from torch.utils.tensorboard import SummaryWriter
# 实例化 SummaryWriter
writer = SummaryWriter(log_dir="./logs") # log_dir 日志存放路径
# 模型训练时,写入train_loss、test_loss、train_acc、test_acc等信息
# 结果放在不同image里
# writer.add_scalar('model/train_Loss', train_loss, epoch)
# writer.add_scalar('model/val_acc', val_acc, epoch)
# 结果可以放在同一image里
writer.add_scalars("loss", {"train_loss": train_loss, "test_loss": test_loss}, epoch)
writer.add_scalars("acc", {"train_acc": train_acc, "test_acc": test_acc}, epoch)
可视化
启动 tensorboard 时,可指定 logdir、port(默认6006)、host(默认localhost)等参数:
例如 :tensorboard --logdir ./logs
损失、准确率曲线图