1. Configuration environment
Use the pip install statement to install Tensorboard in the console (tensorflow needs to be installed at the same time)
pip install tensorflow
pip install tensorboard
Add a reference and set a path for it
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter(log_dir = '日志路径')
2. About SummaryWiter
SummaryWriter is the core of Tensorboard. After the declaration, Tensorboard will start the service, and then you can access the data visually in the browser; you also need to use the close statement to close the service after use. Similar to flask's app.run
writer.close()
3. Add data
Generally speaking, commonly used functions are: add_scalar (add scalar), add_scalars, add_image (add image), and its usage is as follows:
1.add_scalar
Used to add scalars, such as loss functions, that can be used to draw graphs.
for i in range(100):
writer.add_scalar(tag="accuracy", # 标签,即数据属于哪一类,不同的标签对应不同的图
scalar_value=i * random.uniform(0.8, 1), # 纵坐标的值
global_step=i # 迭代次数,即图的横坐标
)
#延迟代码,与数据无关
time.sleep(2 * random.uniform(0.5, 1.5))
Tips.Tag can be split using / (such as: record/avg_loss; record/total_loss), which will put multiple images under the same Tag
2.add_scalars
Add multiple graph lines to the same graph
for epoch in range(100):
writer.add_scalars('scalar/scalars_test', {'xsinx': epoch * np.sin(epoch), 'xcosx': epoch * np.cos(epoch)}, epoch)
3.add_graph
Import the model to realize model visualization
model = Net1() #实例化模型
with SummaryWriter(comment='Net1') as w:
w.add_graph(model, (dummy_input,))
The second parameter is the input vector , which can also be initialized by the following method
init_img = torch.zeros((1, 3, 224, 224), device=device)
4.add_image
To add an image file, you need to specify the channel format (dataformats)
single write
writer.add_image(tag = "test", img_array,1, dataformats='HWC')
multiple write
The pictures need to be packaged into a batch first , and then passed in uniformly
for i in range(16):
img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i
img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i
writer.add_images('my_image_batch', img_batch, 0)