Change tags in tfevents file

Modified from How do you edit an existing Tensorboard Training Loss summary?
TensorFlow version: 2.7.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- coding: utf-8 -*-
import sys
import tensorflow as tf
from pathlib import Path
from tensorflow.compat.v1 import Event


def rename_events(input_path, output_path, old_tags, new_tag):
with tf.io.TFRecordWriter(str(output_path)) as writer:
for rec in tf.data.TFRecordDataset([str(input_path)]):
ev = Event()
ev.MergeFromString(rec.numpy())
if ev.summary:
for v in ev.summary.value:
if v.tag in old_tags:
v.tag = new_tag
writer.write(ev.SerializeToString())


def rename_events_dir(input_dir, output_dir, old_tags, new_tag):
input_dir = Path(input_dir)
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
for ev_file in input_dir.glob('**/*.tfevents*'):
out_file = Path(output_dir, ev_file.relative_to(input_dir))
out_file.parent.mkdir(parents=True, exist_ok=True)
rename_events(ev_file, out_file, old_tags, new_tag)


if __name__ == '__main__':
if len(sys.argv) != 5:
print(f'{sys.argv[0]} <input dir> <output dir> <old tags> <new tag>',
file=sys.stderr)
sys.exit(1)
input_dir, output_dir, old_tags, new_tag = sys.argv[1:]
old_tags = old_tags.split(';')
rename_events_dir(input_dir, output_dir, old_tags, new_tag)
print('Done')