Python 写入训练日志文件并控制台输出解析
作者:SiyuanChen 时间:2021-10-11 01:27:10
1. 背景
在深度学习的任务中,通常需要比较长时间的训练,因此我们会选择离开电脑。笔者在跟踪模型表现,
观察模型accuracy 以及 loss 的时候,比较传统的方法是在控制台print输出或者直接使用tensorboard。
但如果是你需要远程观察模型表现,那一个时刻记录的log 文件就非常重要。
(如果你希望不在实验室,远程通过访问正在训练网络的服务器的Jupyter Notebook ,实时查看实验进度。请参考——远程连接服务器端Jupyter Notebook)
2. logging 函数
创建 .log 文件并将一些数据在控制台输出可以通过logging 函数实现。
废话不多,直接贴代码:一下函数可以在你想要保存日志文件的路径——output_dir下生成一个.log 文件,文件名以年.月.日.时.分命名,以免重复。
import logging
import time
import os
def log_creater(output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
log_name = '{}.log'.format(time.strftime('%Y-%m-%d-%H-%M'))
final_log_file = os.path.join(output_dir,log_name)
# creat a log
log = logging.getLogger('train_log')
log.setLevel(logging.DEBUG)
# FileHandler
file = logging.FileHandler(final_log_file)
file.setLevel(logging.DEBUG)
# StreamHandler
stream = logging.StreamHandler()
stream.setLevel(logging.DEBUG)
# Formatter
formatter = logging.Formatter(
'[%(asctime)s][line: %(lineno)d] ==> %(message)s')
# setFormatter
file.setFormatter(formatter)
stream.setFormatter(formatter)
# addHandler
log.addHandler(file)
log.addHandler(stream)
log.info('creating {}'.format(final_log_file))
return log
3. 结果
保存后的日志文件差不多就是这样:
来源:https://www.cnblogs.com/siyuan1998/p/10886958.html
标签:python,写入,日志,文件,控制台,输出
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python列出一个文件夹及其子目录的所有文件
2023-12-08 17:49:01
浅谈Python类的单继承相关知识
2023-07-31 15:18:53
Python 的可变和不可变对象详情
2021-11-24 22:28:33
![](https://img.aspxhome.com/file/2023/2/87642_0s.png)
Python OpenCV 直方图的计算与显示的方法示例
2022-10-15 07:36:24
![](https://img.aspxhome.com/file/2023/8/120938_0s.jpg)
W3C优质网页小贴士(一)
2008-04-06 16:35:00
![](https://img.aspxhome.com/file/UploadPic/up/2008040712541063.gif)
python实现简单的购物程序代码实例
2022-09-03 05:29:13
关于PyQt5主窗口图标显示问题汇总
2022-03-27 08:23:18
![](https://img.aspxhome.com/file/2023/9/85029_0s.png)
Python3之外部文件调用Django程序操作model等文件实现方式
2023-07-19 01:17:29
go日志库中的logrus
2023-07-21 13:48:02
Python 模块EasyGui详细介绍
2022-04-27 22:55:39
Python基础学习之函数和代码复用详解
2022-11-17 13:05:38
![](https://img.aspxhome.com/file/2023/7/71467_0s.png)
每个程序员都应该学习使用Python或Ruby
2023-09-05 06:03:52
![](https://img.aspxhome.com/file/2023/2/130932_0s.png)
用CSS实现柱状图(Bar Graph)的方法(四)—table实现复杂柱状图
2008-05-28 12:55:00
![](https://img.aspxhome.com/file/UploadPic/20085/28/200852813283924s.jpg)
IE中不可遍历的属性
2010-01-19 13:47:00
Python获取脚本所在目录的正确方法
2022-12-07 14:37:36
TensorFlow绘制loss/accuracy曲线的实例
2022-01-25 08:01:16
![](https://img.aspxhome.com/file/2023/0/95170_0s.jpg)
IE6绝对定位的bug及其解决办法
2011-03-30 12:31:00
Oracle常见错误诊断
2010-07-27 12:56:00
Python matplotlib学习笔记之坐标轴范围
2022-04-21 16:24:28
![](https://img.aspxhome.com/file/2023/8/88038_0s.jpg)
Python入门篇之字符串
2022-01-09 00:31:17