Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TensorFlow-从TensorBoard TFEvent文件导入数据?_Python_Tensorflow_Tensorboard - Fatal编程技术网

Python TensorFlow-从TensorBoard TFEvent文件导入数据?

Python TensorFlow-从TensorBoard TFEvent文件导入数据?,python,tensorflow,tensorboard,Python,Tensorflow,Tensorboard,我已经用TensorFlow中的不同图表进行了几次培训。我设置的摘要显示了培训和验证中有趣的结果。现在,我想获取我保存在摘要日志中的数据,执行一些统计分析,并以不同的方式绘制和查看摘要数据。是否有任何现有方法可以轻松访问此数据 更具体地说,是否有任何内置方法可以将TFEvent记录读回Python 如果没有简单的方法可以做到这一点。根据我对protobufs的理解(这是有限的),我认为如果我有TFEvent协议规范,我就能够提取这些数据。有没有一个简单的方法来控制这个?非常感谢。您只需使用: t

我已经用TensorFlow中的不同图表进行了几次培训。我设置的摘要显示了培训和验证中有趣的结果。现在,我想获取我保存在摘要日志中的数据,执行一些统计分析,并以不同的方式绘制和查看摘要数据。是否有任何现有方法可以轻松访问此数据

更具体地说,是否有任何内置方法可以将TFEvent记录读回Python

如果没有简单的方法可以做到这一点。根据我对protobufs的理解(这是有限的),我认为如果我有TFEvent协议规范,我就能够提取这些数据。有没有一个简单的方法来控制这个?非常感谢。

您只需使用:

tensorboard --inspect --event_file=myevents.out
或者,如果要筛选图表中特定事件的子集,请执行以下操作:

tensorboard --inspect --event_file=myevents.out --tag=loss
如果您想创建更多自定义的内容,可以深入

/tensorflow/python/summary/event_file_inspector.py 
了解如何解析事件文件。

作为Fabrizio,TensorBoard是可视化摘要日志内容的绝佳工具。但是,如果要执行自定义分析,可以使用函数在日志中的所有和协议缓冲区上循环:

for summary in tf.train.summary_iterator("/path/to/log/file"):
    # Perform custom processing in here.
tf2的更新:

from tensorflow.python.summary.summary_iterator import summary_iterator
您需要导入它,默认情况下当前未导入该模块级别。在2.0.0-rc2上,您可以使用脚本,它将接收一个logdir并以json格式写出所有数据


您还可以使用一个方便的Python API(这与TensorBoard使用的API相同)。

要读取TFEvent,您可以获得一个生成事件协议缓冲区的Python迭代器

# This example supposes that the events file contains summaries with a
# summary value tag 'loss'.  These could have been added by calling
# `add_summary()`, passing the output of a scalar summary op created with
# with: `tf.scalar_summary(['loss'], loss_tensor)`.
for e in tf.train.summary_iterator(path_to_events_file):
    for v in e.summary.value:
        if v.tag == 'loss' or v.tag == 'accuracy':
            print(v.simple_value)

更多信息:

这里是一个从标量获取值的完整示例。您可以看到事件protobuf消息的消息规范


我一直在用这个。它假定您只希望看到记录了多次的标记,这些标记的值是浮动的,并以
pd.DataFrame
的形式返回结果。只需调用
metrics\u df=parse\u events\u file(path)


从tensorflow版本
2.0.0-beta1起,以下工作:

import os

import tensorflow as tf
from tensorflow.python.framework import tensor_util

summary_dir = 'tmp/summaries'
summary_writer = tf.summary.create_file_writer('tmp/summaries')

with summary_writer.as_default():
  tf.summary.scalar('loss', 0.1, step=42)
  tf.summary.scalar('loss', 0.2, step=43)
  tf.summary.scalar('loss', 0.3, step=44)
  tf.summary.scalar('loss', 0.4, step=45)


from tensorflow.core.util import event_pb2
from tensorflow.python.lib.io import tf_record

def my_summary_iterator(path):
    for r in tf_record.tf_record_iterator(path):
        yield event_pb2.Event.FromString(r)

for filename in os.listdir(summary_dir):
    path = os.path.join(summary_dir, filename)
    for event in my_summary_iterator(path):
        for value in event.summary.value:
            t = tensor_util.MakeNdarray(value.tensor)
            print(value.tag, event.step, t, type(t))

my_summary_iterator
的代码是从
tensorflow.python.summary.summary_iterator.py
复制的-无法在运行时导入它。

2020年后期版本的tensorflow和tensorflow数据集建议采用不同的方法。使用和:


这适用于TensorFlow的哪个版本?我使用的是
0.8
。对我来说,
--logdir
始终是必需的,尽管传入了这些其他参数,但TensorBoard似乎还是照常运行,忽略了这些参数。此外,
--help
不显示这些参数中的任何一个。另外,为了确保我没有遗漏一些东西,这是不是要在终端屏幕上打印一些东西?或者更改张力板页面上显示的内容?还是别的什么?谢谢根据这一线索,我找到了
eventacculator
类。加载文件后,可以提供汇总值的所有详细信息。我将更详细地更新您的答案。事实上,这些参数在tensorflow tip中提供。我明白了。它似乎是一周前才添加的。谢谢从Tensorboard 1.1版开始,serialize_Tensorboard脚本不再可用。这里有一些很好的助手函数,我们在TensorFlow 1.8+中没有。现在似乎更改为
tf.python.summary.summary\u迭代器
。在TF2中找不到摘要迭代器时间已经过去,现在可以在
tf.compat.v1.train
下找到
summary\u迭代器
。此外,Tensorboard包还为不想依赖Tensorflow的用户提供了
Tensorboard.backend.event\u处理
模块。有关详细信息,请参阅我正在分析由tensorflow对象检测api生成的tfevent文件,因此,只需使用
值。简单的\u值
总是产生
0
,即使在tensorboard gui中,数字明显不同。这行
t=tensor\u util.makendaray(value.tensor)
似乎能帮你搞定这个!在tensorflow 2.4中,至少需要
tensor_util.MakeNdarray(value.tensor)
来访问该值,如果该值是自定义度量,而不是keras的默认值。如果您使用
tf.summary.scalar()
编写它,出于某种原因,它会被保存为张量而不是标量,并且
值。simple\u value
始终返回
0
from collections import defaultdict
import pandas as pd
import tensorflow as tf

def is_interesting_tag(tag):
    if 'val' in tag or 'train' in tag:
        return True
    else:
        return False


def parse_events_file(path: str) -> pd.DataFrame:
    metrics = defaultdict(list)
    for e in tf.train.summary_iterator(path):
        for v in e.summary.value:

            if isinstance(v.simple_value, float) and is_interesting_tag(v.tag):
                metrics[v.tag].append(v.simple_value)
            if v.tag == 'loss' or v.tag == 'accuracy':
                print(v.simple_value)
    metrics_df = pd.DataFrame({k: v for k,v in metrics.items() if len(v) > 1})
    return metrics_df
import os

import tensorflow as tf
from tensorflow.python.framework import tensor_util

summary_dir = 'tmp/summaries'
summary_writer = tf.summary.create_file_writer('tmp/summaries')

with summary_writer.as_default():
  tf.summary.scalar('loss', 0.1, step=42)
  tf.summary.scalar('loss', 0.2, step=43)
  tf.summary.scalar('loss', 0.3, step=44)
  tf.summary.scalar('loss', 0.4, step=45)


from tensorflow.core.util import event_pb2
from tensorflow.python.lib.io import tf_record

def my_summary_iterator(path):
    for r in tf_record.tf_record_iterator(path):
        yield event_pb2.Event.FromString(r)

for filename in os.listdir(summary_dir):
    path = os.path.join(summary_dir, filename)
    for event in my_summary_iterator(path):
        for value in event.summary.value:
            t = tensor_util.MakeNdarray(value.tensor)
            print(value.tag, event.step, t, type(t))
from os import path, listdir
from operator import contains
from functools import partial
from itertools import chain
from json import loads

import numpy as np
import tensorflow as tf
from tensorflow.core.util import event_pb2

# From https://github.com/Suor/funcy/blob/0ee7ae8/funcy/funcs.py#L34-L36
def rpartial(func, *args):
    """Partially applies last arguments."""
    return lambda *a: func(*(a + args))


tensorboard_logdir = "/tmp"


# Or you could just glob… for *tfevents*:
list_dir = lambda p: map(partial(path.join, p), listdir(p))

for event in filter(rpartial(contains, "tfevents"),
                    chain.from_iterable(
                        map(list_dir,
                            chain.from_iterable(
                                map(list_dir,
                                    filter(rpartial(contains, "_epochs_"),
                                           list_dir(tensorboard_logdir))))))):
    print(event)
    for raw_record in tf.data.TFRecordDataset(event):
        for value in event_pb2.Event.FromString(raw_record.numpy()).summary.value:
            print("value: {!r} ;".format(value))
            if value.tensor.ByteSize():
                t = tf.make_ndarray(value.tensor)
                if hasattr(event, "step"):
                    print(value.tag, event.step, t, type(t))
                elif type(t).__module__ == np.__name__:
                    print("t: {!r} ;".format(np.vectorize(loads)(t)))
    print()