部分测试代码:
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image
import torch
import cv2 as cv
import matplotlib.pyplot as plt
from torch import nn
from torchvision import datasets
def functiontools():
writer = SummaryWriter("logs");
#绘制一次函数
for i in range(1, 101):
writer.add_scalar('y = 2x', i, 2 * i)
#回执2次函数
for i in range(-500, 500):
writer.add_scalar("y=x*x", i * i, i)
#绘制三次函数
for i in range(-500, 500):
writer.add_scalar("y=x*x*x", i * i * i, i)
r = 5
#绘制多曲线
for i in range(1, 101):
writer.add_scalars('run_14h', {'xsinx': i * np.sin(i / r),
'xcosx': i * np.cos(i / r),
'xtanx': i * np.tan(i / r)}, i)
#绘制直方图
for step in range(10):
i = np.random.randn(1000)
writer.add_histogram('distribution of gaussion', i, step)
# 渲染(figure)
x = np.linspace(0, 10, 1000)
y = np.sin(x)
figure1 = plt.figure()
plt.plot(x, y, 'r-')
writer.add_figure('my_figure', figure1, 0)
dataset = datasets.MNIST('mnist', train=False, download=True)
images = dataset.test_data[:100].float()
label = dataset.test_labels[:100]
features = images.view(100, 784)
writer.add_embedding(features, metadata=label, label_img=images.unsqueeze(1))
writer.close()
def image():
image_path = "../0e630643930fb8778aa59b6bfaceccc.png" # 图片路径
# 读取图片的两种方式:
img_PIL = Image.open(image_path) # 方式一
# img_PIL = cv2.imread(image_path) # 方式二
img_array = np.array(img_PIL)
writer = SummaryWriter("logs") # 文件夹“logs”
writer.add_image('ant', img_array, 1, dataformats='HWC')
# 或者
img = cv.imread('zhou.jpg', cv.IMREAD_COLOR) # 输入图像要是3通道的,所以读取彩色图像
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
img = torch.tensor(img.transpose(2, 0, 1)) # cv读取为numpy图像为(H * W * C),所以要进行轴转换
writer.add_image('CIRAF-10', img, 0)
writer.close()
# 网络(graph)
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.Net = nn.Sequential(
nn.Linear(784, 512),
nn.ReLU(),
nn.Linear(512, 128),
nn.ReLU(),
nn.Linear(128, 10)
)
def forward(self, input):
input = input.view(-1, 28 * 28)
return self.Net(input)
def net():
model = MLP()
input = torch.FloatTensor(np.random.rand(32, 1, 28, 28))
writer = SummaryWriter("logs") # 文件夹“logs”
writer.add_graph(model, input)
writer.close()
if __name__ =='__main__':
#函数
functiontools()
#图片
image()
安装:
pip install tensorboard
运行:
tensorboard --logdir=httdemo/logs --port=6007#自己制定显示的端口号
后续的一些功能:
# 7. add_text() # add_text(tag, text_string, global_step=None, walltime=None) # 功能:记录文字 # 8. add_video() # add_video(tag, vid_tensor, global_step=None, fps=4, walltime=None) # 功能:记录 video # 9. add_figure() # add_figure(tag, figure, global_step=None, close=True, walltime=None) # 功能:添加 matplotlib 图片到图像中 # 10. add_image_with_boxes() # add_image_with_boxes(tag, img_tensor, box_tensor, global_step=None, walltime=None, **kwargs) # 功能:图像中绘制 Box,目标检测中会用到 # 11. add_pr_curve() # add_pr_curve(tag, labels, predictions, global_step=None, num_thresholds=127, weights=None, walltime=None) # 功能:绘制 PR 曲线 # 12. add_pr_curve_raw() # add_pr_curve_raw(tag, true_positive_counts, false_positive_counts, true_negative_counts, false_negative_counts, precision, recall, global_step=None, num_thresholds=127, weights=None, walltime=None) # 功能:从原始数据上绘制 PR 曲线 # 13. export_scalars_to_json() # export_scalars_to_json(path)