提取log文件中的数据,画图

  1. 要提取的log格式如下:

  1. 代码如下:

python 复制代码
import re

import matplotlib.pyplot as plt
import numpy as np

import argparse
from os import path
from re import search


class DataExtractor(object):
    ''' DataExtrator class '''

    def __init__(self, infile, keyword, outfile):
        '''
        构造函数

        infile:输入文件名
        keyword:目标数据前面的关键字
        outfile:输出文件名
        '''

        self.infile = infile
        self.keyword = keyword
        self.outfile = outfile

    def data_after_keyword(self):
        ''' Extract data from infile after the keyword. '''

        try:
            data = []
            patt = '%s:\s*(\d+\.?\d+)' % self.keyword  # 使用正则表达式搜索数据,关键字冒号,有空格或者没有空格,  小数点前后的数字
            with open(self.infile, 'r') as fi:
                with open(self.outfile, 'w') as fo:
                    for eachLine in fi:
                        s = search(patt, eachLine)
                        if s is not None:
                            fo.write(s.group(1) + '\n')
                            data.append(float(s.group(1)))
            return data
        except IOError:
            print(
                "Open file [%s] or [%s] failed!" % (self.infile, self.outfile))
            return False


if __name__ == "__main__":

    names = ['train loss', 'train psnr', 'iter_time', 'data_time', 'epoch time']
    file = r'D:\512_bs4_20230922_182434.log'
    fileout = file[:-4] + '_out.log'

    dd = dict()
    for name in names:
        extractor = DataExtractor(file, name, fileout)
        dd[name] = extractor.data_after_keyword()
    print(dd)

    x = range(len(dd[names[0]]))
    plt.figure()
    plt.subplot(131)
    plt.plot(x, dd[names[0]], 'r')
    plt.subplot(132)
    plt.plot(x, dd[names[1]], 'r')
    plt.subplot(133)
    plt.plot(x, dd[names[2]], 'g', x, dd[names[3]], 'b')
    plt.show()
  1. 得到结果

参考:

https://blog.csdn.net/guo_qingxia/article/details/113979135

https://blog.csdn.net/letian3658/article/details/105882965

相关推荐
高洁016 小时前
具身智能中的世界模型训练
人工智能·python·深度学习·机器学习·transformer
无线通信科研笔记6 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
朝朝辞暮i6 小时前
VLA 系统学习第 1 课:VLA 到底在干什么?
人工智能·python·计算机视觉·vla
2601_962885727 小时前
如何用 Python 自动识别股票的支撑位与压力位?
开发语言·python
北冥有鱼被烹7 小时前
VCSEL全景解析:与光模块NPO CPO的关系、市场量化分析与产业链影响
python
caoerzhong8 小时前
中小企业上 WMS 该先上哪几块:JeeWMS 开源 Java 仓库管理系统的分批上线清单
java·python·开源
正在走向自律8 小时前
AI数据分析与可视化:从基础到应用实践
服务器·人工智能·python·机器学习·数据分析·pandas
databook8 小时前
从手动检查到自动监控:一个数据质量工作流的实现
后端·python·数据分析
北冥有鱼被烹11 小时前
砷化镓与磷化铟:光模块的地基——从化学键到AI缺货潮的底层逻辑
人工智能·python
for_ever_love__12 小时前
线性回归与梯度下降——从零手写一个模型
python·机器学习·线性回归·梯度下降