Skip to main content
 首页 » 编程设计

python之从 Tensorflow 摘要中获取 CSV

2024年10月01日30kuangbin

我有一些非常大的 tensorflow 摘要。如果这些是使用 tensorboard 绘制的,我可以从中下载 CSV 文件。

但是,使用 tensorboard 绘制这些图会花费很长时间。我在 the docs 中找到有一种方法可以直接在 Python 中读取摘要。此方法是 summary_iterator,可以按如下方式使用:

import tensorflow as tf 
 
for e in tf.train.summary_iterator(path to events file): 
    print(e) 

我可以使用这种方法直接创建CSV文件吗?如果是这样,我该怎么做?这会节省很多时间。

请您参考如下方法:

一种可能的做法是这样的:

from tensorboard.backend.event_processing import event_accumulator       
import numpy as np 
import pandas as pd 
import sys 
 
def create_csv(inpath, outpath): 
    sg = {event_accumulator.COMPRESSED_HISTOGRAMS: 1, 
          event_accumulator.IMAGES: 1, 
          event_accumulator.AUDIO: 1, 
          event_accumulator.SCALARS: 0, 
          event_accumulator.HISTOGRAMS: 1} 
    ea = event_accumulator.EventAccumulator(inpath, size_guidance=sg) 
    ea.Reload() 
    scalar_tags = ea.Tags()['scalars'] 
    df = pd.DataFrame(columns=scalar_tags) 
    for tag in scalar_tags: 
        events = ea.Scalars(tag) 
        scalars = np.array(map(lambda x: x.value, events)) 
        df.loc[:, tag] = scalars 
    df.to_csv(outpath) 
 
if __name__ == '__main__': 
    args = sys.argv 
    inpath = args[1] 
    outpath = args[2] 
    create_csv(inpath, outpath) 

请注意,此代码会将整个事件文件加载到内存中,因此最好在集群上运行它。有关 EventAccumulator 的 sg 参数的信息,请参阅 this SO question .

一个额外的改进可能是不仅存储每个标量的值,而且还存储步骤。

注意代码片段已针对 TF 的最新版本进行了更新。 对于 TF < 1.1,请改用以下导入:

from tensorflow.tensorboard.backend.event_processing import event_accumulator as eva