一、安裝TensorBoard
管理員身份運行Anaconda Prompt,進入自己的環境環境 conda activate y_pytorch
,pip install tensorboard
進行下載,也可以通過conda install tensorboard
進行下載。其實通俗點,pip相當于菜市場,conda相當于大型正規超市。
二、SummaryWriter類
所有編譯均在PyChram下進行
from torch.utils.tensorboard import SummaryWriter
按著Ctrl,點擊SummaryWriter,進入查看該類的使用說明文檔
"""Writes entries directly to event files in the log_dir to beconsumed by TensorBoard. 將條目直接寫入log_dir中的事件文件,供TensorBoard使用The `SummaryWriter` class provides a high-level API to create an event filein a given directory and add summaries and events to it. The class updates thefile contents asynchronously. This allows a training program to call methodsto add data to the file directly from the training loop, without slowing downtraining."""看不懂沒關系,DL翻譯一下就行了唄,大概就是,SummaryWriter類會生成一個文件,這個文件會被TensorBoard所解析使用,也就是說可以通過TensorBoard進行可視化展示
#這個是SummaryWriter的初始化函數def __init__(self, log_dir=None, comment='', purge_step=None, max_queue=10,flush_secs=120, filename_suffix=''):"""Creates a `SummaryWriter` that will write out events and summariesto the event file.Args:log_dir (string): Save directory location. Default isruns/**CURRENT_DATETIME_HOSTNAME**, which changes after each run.Use hierarchical folder structure to comparebetween runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.for each new experiment to compare across them.
#保存的文件為log_dir所指定的位置,默認為runs/**CURRENT_DATETIME_HOSTNAME**這個位置#同理,后面的參數可以進行翻譯,然后進行學習即可comment (string): Comment log_dir suffix appended to the default``log_dir``. If ``log_dir`` is assigned, this argument has no effect.purge_step (int):When logging crashes at step :math:`T+X` and restarts at step :math:`T`,any events whose global_step larger or equal to :math:`T` will bepurged and hidden from TensorBoard.Note that crashed and resumed experiments should have the same ``log_dir``.max_queue (int): Size of the queue for pending events andsummaries before one of the 'add' calls forces a flush to disk.Default is ten items.flush_secs (int): How often, in seconds, to flush thepending events and summaries to disk. Default is every two minutes.filename_suffix (string): Suffix added to all event filenames inthe log_dir directory. More details on filename construction intensorboard.summary.writer.event_file_writer.EventFileWriter.Examples::
#如何使用,使用案例from torch.utils.tensorboard import SummaryWriter# create a summary writer with automatically generated folder name.writer = SummaryWriter()# folder location: runs/May04_22-14-54_s-MacBook-Pro.local/
#參數啥都不加,默認生成的文件會放入runs/May04_22-14-54_s-MacBook-Pro.local/位置# create a summary writer using the specified folder name.writer = SummaryWriter("my_experiment")# folder location: my_experiment
#指定位置,生成的文件會放入指定位置# create a summary writer with comment appended.writer = SummaryWriter(comment="LR_0.1_BATCH_16")# folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/"""
了解完SummaryWriter之后,開始為其創建對象
writer = SummaryWriter("y_log")#對應生成的文件會放入y_log文件夾下
三、add_scalar()方法
將標量數據添加到summary中
writer.add_scalar()#按住Ctrl,點擊add_scalar方法,查看該方法的使用說明
"""Add scalar data to summary.
#將標量數據添加到summary中Args:#參數tag (string): Data identifier
#圖標的title名稱scalar_value (float or string/blobname): Value to save
#要保存的數據值,一般用作y軸global_step (int): Global step value to record
#記錄全局的步長值,一般用作x軸walltime (float): Optional override default walltime (time.time())with seconds after epoch of eventnew_style (boolean): Whether to use new style (tensor field) or oldstyle (simple_value field). New style could lead to faster data loading.Examples::from torch.utils.tensorboard import SummaryWriterwriter = SummaryWriter()x = range(100)for i in x:writer.add_scalar('y=2x', i * 2, i)writer.close()Expected result:.. image:: _static/img/tensorboard/add_scalar.png:scale: 50 %"""
繪制一個y=3*x的圖,通過tensorboard進行展示
from torch.utils.tensorboard import SummaryWriterwriter = SummaryWriter("y_log")#文件所存放的位置在y_log文件夾下for i in range(100):writer.add_scalar("y=3*x",3*i,i)#圖標的title為y=3*x,y軸為3*i,x軸為i
#要注意的是title若一樣,則會發生擬合現象,會出錯。一般不同圖像要對應不同的title,一個title會對應一張圖。writer.close()
運行完之后,發現多了個文件夾,里面存放的就是tensorboard的一些事件文件
在Terminal下運行tensorboard --logdir=y_log --port=7870
,logdir為打開事件文件的路徑,port為指定端口打開;
通過指定端口7870進行打開tensorboard,若不設置port參數,默認通過6006端口進行打開。
點擊該鏈接或者復制鏈接到瀏覽器打開即可
四、add_image()方法
將圖像數據添加到summary中
同樣的道理,進行查看該方法的使用說明
writer.add_image()#按住Ctrl,點擊aadd_image方法,查看該方法的使用說明
"""Add image data to summary.
#將圖像數據添加到summary中Note that this requires the ``pillow`` package.Args:#參數tag (string): Data identifier
#對數據的定義,也就是在tensorboard中顯示的時候title是啥 img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data
#這里對圖像的要求必須是這幾類,需要將圖片類型進行轉換global_step (int): Global step value to record
#記錄的全局步長,也就是第幾張圖片walltime (float): Optional override default walltime (time.time())seconds after epoch of eventShape:img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` toconvert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job.Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long ascorresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``.
##圖片的類型應該為(3, H, W),若不一樣則可以通過dataformats參數進行設置Examples::from torch.utils.tensorboard import SummaryWriterimport numpy as npimg = np.zeros((3, 100, 100))img[0] = np.arange(0, 10000).reshape(100, 100) / 10000img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000img_HWC = np.zeros((100, 100, 3))img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000writer = SummaryWriter()writer.add_image('my_image', img, 0)# If you have non-default dimension setting, set the dataformats argument.writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC')writer.close()Expected result:.. image:: _static/img/tensorboard/add_image.png:scale: 50 %"""
添加圖片到tensorboard中
from torch.utils.tensorboard import SummaryWriter
import cv2 as cv
import numpy as npwriter = SummaryWriter("y_log")img_path = "G:/PyCharm/workspace/learning_pytorch/dataset/a/1.jpg"
img = cv.imread(img_path)
img_array = np.array(img)
print(type(img_array))#<class 'numpy.ndarray'> 滿足該方法img_tensor類型
print(img_array.shape)#(499, 381, 3) 這里看到是(H, W, 3),并不是人家指定的(3, H, W),需要設置dataformats來聲明該數據規格為HWCwriter.add_image("beyond",img_array,0,dataformats="HWC")#將來在tensorbord顯示的title為beyondwriter.close()
在Terminal下運行tensorboard --logdir=y_log --port=7870
,logdir為打開事件文件的路徑,port為指定端口打開;
通過指定端口7870進行打開tensorboard,若不設置port參數,默認通過6006端口進行打開。
點擊該鏈接或者復制鏈接到瀏覽器打開即可