PyTorch torch.utils.tensorboard

2020-09-15 12:01 更新

原文: PyTorch torch.utils.tensorboard

安裝 TensorBoard 后,這些實(shí)用程序使您可以將 PyTorch 模型和指標(biāo)記錄到目錄中,以便在 TensorBoard UI 中進(jìn)行可視化。 PyTorch 模型和張量以及 Caffe2 網(wǎng)絡(luò)和 Blob 均支持標(biāo)量,圖像,直方圖,圖形和嵌入可視化。

SummaryWriter 類是您用來登錄數(shù)據(jù)以供 TensorBoard 使用和可視化的主要條目。 例如:

  1. import torch
  2. import torchvision
  3. from torch.utils.tensorboard import SummaryWriter
  4. from torchvision import datasets, transforms
  5. ## Writer will output to ./runs/ directory by default
  6. writer = SummaryWriter()
  7. transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
  8. trainset = datasets.MNIST('mnist_train', train=True, download=True, transform=transform)
  9. trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
  10. model = torchvision.models.resnet50(False)
  11. ## Have ResNet model take in grayscale rather than RGB
  12. model.conv1 = torch.nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
  13. images, labels = next(iter(trainloader))
  14. grid = torchvision.utils.make_grid(images)
  15. writer.add_image('images', grid, 0)
  16. writer.add_graph(model, images)
  17. writer.close()

然后可以使用 TensorBoard 對其進(jìn)行可視化,該 TensorBoard 應(yīng)該可通過以下方式安裝和運(yùn)行:

  1. pip install tensorboard
  2. tensorboard --logdir=runs

一個實(shí)驗(yàn)可以記錄很多信息。 為了避免 UI 混亂和更好地將結(jié)果聚類,我們可以通過對圖進(jìn)行分層命名來對圖進(jìn)行分組。 例如,“損失/火車”和“損失/測試”將被分組在一起,而“準(zhǔn)確性/火車”和“準(zhǔn)確性/測試”將在 TensorBoard 界面中分別分組。

  1. from torch.utils.tensorboard import SummaryWriter
  2. import numpy as np
  3. writer = SummaryWriter()
  4. for n_iter in range(100):
  5. writer.add_scalar('Loss/train', np.random.random(), n_iter)
  6. writer.add_scalar('Loss/test', np.random.random(), n_iter)
  7. writer.add_scalar('Accuracy/train', np.random.random(), n_iter)
  8. writer.add_scalar('Accuracy/test', np.random.random(), n_iter)

預(yù)期結(jié)果:

_images/hier_tags.png

  1. class torch.utils.tensorboard.writer.SummaryWriter(log_dir=None, comment='', purge_step=None, max_queue=10, flush_secs=120, filename_suffix='')?

將條目直接寫入 log_dir 中的事件文件,以供 TensorBoard 使用。

<cite>SummaryWriter</cite> 類提供了一個高級 API,用于在給定目錄中創(chuàng)建事件文件并向其中添加摘要和事件。 該類異步更新文件內(nèi)容。 這允許訓(xùn)練程序從訓(xùn)練循環(huán)中調(diào)用直接將數(shù)據(jù)添加到文件的方法,而不會減慢訓(xùn)練速度。

  1. __init__(log_dir=None, comment='', purge_step=None, max_queue=10, flush_secs=120, filename_suffix='')?

創(chuàng)建一個 <cite>SummaryWriter</cite> ,它將事件和摘要寫到事件文件中。

參數(shù)

  • log_dir (字符串)–保存目錄位置。 默認(rèn)值為運(yùn)行次數(shù)/ CURRENT_DATETIME_HOSTNAME ,每次運(yùn)行后都會更改。 使用分層文件夾結(jié)構(gòu)可以輕松比較運(yùn)行情況。 例如 為每個新實(shí)驗(yàn)傳遞“ runs / exp1”,“ runs / exp2”等,以便在它們之間進(jìn)行比較。
  • 注釋(字符串)–注釋 log_dir 后綴附加到默認(rèn)值log_dir。 如果分配了log_dir,則此參數(shù)無效。
  • purge_step (python:int )–當(dāng)日志記錄在步驟img崩潰并在步驟img重新啟動時,將清除 global_step 大于或等于img的所有事件, 隱藏在 TensorBoard 中。 請注意,崩潰的實(shí)驗(yàn)和恢復(fù)的實(shí)驗(yàn)應(yīng)具有相同的log_dir
  • max_queue (python:int )–在“添加”調(diào)用之一強(qiáng)行刷新到磁盤之前,未決事件和摘要的隊(duì)列大小。 默認(rèn)值為十個項(xiàng)目。
  • flush_secs (python:int )–將掛起的事件和摘要刷新到磁盤的頻率(以秒為單位)。 默認(rèn)值為每兩分鐘一次。
  • filename_suffix (字符串)–后綴添加到 log_dir 目錄中的所有事件文件名中。 在 tensorboard.summary.writer.event_file_writer.EventFileWriter 中有關(guān)文件名構(gòu)造的更多詳細(xì)信息。

例子:

  1. from torch.utils.tensorboard import SummaryWriter
  2. ## create a summary writer with automatically generated folder name.
  3. writer = SummaryWriter()
  4. ## folder location: runs/May04_22-14-54_s-MacBook-Pro.local/
  5. ## create a summary writer using the specified folder name.
  6. writer = SummaryWriter("my_experiment")
  7. ## folder location: my_experiment
  8. ## create a summary writer with comment appended.
  9. writer = SummaryWriter(comment="LR_0.1_BATCH_16")
  10. ## folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/

  1. add_scalar(tag, scalar_value, global_step=None, walltime=None)?

將標(biāo)量數(shù)據(jù)添加到摘要中。

Parameters

  • 標(biāo)記(字符串)–數(shù)據(jù)標(biāo)識符
  • 標(biāo)量值 (python:float 字符串/名稱)–要保存的值
  • global_step (python:int )–要記錄的全局步長值
  • walltime (python:float )–可選,以事件發(fā)生后的秒數(shù)覆蓋默認(rèn)的 walltime(time.time())

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. writer = SummaryWriter()
  3. x = range(100)
  4. for i in x:
  5. writer.add_scalar('y=2x', i * 2, i)
  6. writer.close()

Expected result:

_images/add_scalar.png

  1. add_scalars(main_tag, tag_scalar_dict, global_step=None, walltime=None)?

將許多標(biāo)量數(shù)據(jù)添加到摘要中。

請注意,此函數(shù)還將已記錄的標(biāo)量保存在內(nèi)存中。 在極端情況下,它會炸毀您的 RAM。

Parameters

  • main_tag (字符串)–標(biāo)記的父名稱
  • tag_scalar_dict (dict )–存儲標(biāo)簽和對應(yīng)值的鍵值對
  • global_step (python:int) – Global step value to record
  • walltime (python:float )–可選的替代默認(rèn)時間 Walltime(time.time())秒

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. writer = SummaryWriter()
  3. r = 5
  4. for i in range(100):
  5. writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r),
  6. 'xcosx':i*np.cos(i/r),
  7. 'tanx': np.tan(i/r)}, i)
  8. writer.close()
  9. ## This call adds three values to the same scalar plot with the tag
  10. ## 'run_14h' in TensorBoard's scalar section.

Expected result:

_images/add_scalars.png

  1. add_histogram(tag, values, global_step=None, bins='tensorflow', walltime=None, max_bins=None)?

將直方圖添加到摘要中。

Parameters

  • tag (string) – Data identifier
  • (torch張量 , numpy.array 字符串/名稱)–建立直方圖的值
  • global_step (python:int) – Global step value to record
  • 容器(字符串)– {'tensorflow','auto','fd',…}中的一種。 這決定了垃圾桶的制作方式。 您可以在以下位置找到其他選項(xiàng): https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. import numpy as np
  3. writer = SummaryWriter()
  4. for i in range(10):
  5. x = np.random.random(1000)
  6. writer.add_histogram('distribution centers', x + i, i)
  7. writer.close()

Expected result:

_images/add_histogram.png

  1. add_image(tag, img_tensor, global_step=None, walltime=None, dataformats='CHW')?

將圖像數(shù)據(jù)添加到摘要。

注意,這需要pillow程序包。

Parameters

  • tag (string) – Data identifier
  • img_tensor (torch張量 , numpy.array 字符串/名稱)–圖像數(shù)據(jù)
  • global_step (python:int) – Global step value to record
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

  1. Shape:

img_tensor:默認(rèn)為img。 您可以使用torchvision.utils.make_grid()將一批張量轉(zhuǎn)換為 3xHxW 格式,或者調(diào)用add_images讓我們完成這項(xiàng)工作。 只要傳遞了相應(yīng)的dataformats自變量,也可以使用帶有imgimgimg的張量。 例如 CHW,HWC,HW。

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. import numpy as np
  3. img = np.zeros((3, 100, 100))
  4. img[0] = np.arange(0, 10000).reshape(100, 100) / 10000
  5. img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000
  6. img_HWC = np.zeros((100, 100, 3))
  7. img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000
  8. img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000
  9. writer = SummaryWriter()
  10. writer.add_image('my_image', img, 0)
  11. ## If you have non-default dimension setting, set the dataformats argument.
  12. writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC')
  13. writer.close()

Expected result:

_images/add_image.png

  1. add_images(tag, img_tensor, global_step=None, walltime=None, dataformats='NCHW')?

將批處理的圖像數(shù)據(jù)添加到摘要中。

Note that this requires the pillow package.

Parameters

  • tag (string) – Data identifier
  • img_tensor (*torch.Tensor*, numpy.array__, or string/blobname) – Image data
  • global_step (python:int) – Global step value to record
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event
  • 數(shù)據(jù)格式(字符串)– NCHW,NHWC,CHW,HWC,HW,WH 等形式的圖像數(shù)據(jù)格式規(guī)范

  1. Shape:

img_tensor:默認(rèn)為img。 如果指定dataformats,將接受其他形狀。 例如 NCHW 或 NHWC。

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. import numpy as np
  3. img_batch = np.zeros((16, 3, 100, 100))
  4. for i in range(16):
  5. img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i
  6. img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i
  7. writer = SummaryWriter()
  8. writer.add_images('my_image_batch', img_batch, 0)
  9. writer.close()

Expected result:

_images/add_images.png

  1. add_figure(tag, figure, global_step=None, close=True, walltime=None)?

將 matplotlib 圖形渲染為圖像,并將其添加到摘要中。

注意,這需要matplotlib程序包。

Parameters

  • tag (string) – Data identifier
  • 圖形 (matplotlib.pyplot.figure )–圖形或圖形列表
  • global_step (python:int) – Global step value to record
  • 關(guān)閉 (bool )–自動關(guān)閉圖形的標(biāo)志
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

  1. add_video(tag, vid_tensor, global_step=None, fps=4, walltime=None)?

將視頻數(shù)據(jù)添加到摘要。

注意,這需要moviepy程序包。

Parameters

  • tag (string) – Data identifier
  • vid_tensor (torch張量)–視頻數(shù)據(jù)
  • global_step (python:int) – Global step value to record
  • fps (python:float python:int )–每秒幀數(shù)
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

  1. Shape:

vid_tensor:img。 對于 <cite>uint8</cite> 類型,值應(yīng)位于[0,255]中;對于 <cite>float</cite> 類型,值應(yīng)位于[0,1]中。

  1. add_audio(tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None)?

將音頻數(shù)據(jù)添加到摘要。

Parameters

  • tag (string) – Data identifier
  • snd_tensor (torch張量)–聲音數(shù)據(jù)
  • global_step (python:int) – Global step value to record
  • sample_rate (python:int )–以 Hz 為單位的采樣率
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

  1. Shape:

snd_tensor:img。 值應(yīng)介于[-1,1]之間。

  1. add_text(tag, text_string, global_step=None, walltime=None)?

將文本數(shù)據(jù)添加到摘要。

Parameters

  • tag (string) – Data identifier
  • text_string (字符串)–要保存的字符串
  • global_step (python:int) – Global step value to record
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

Examples:

  1. writer.add_text('lstm', 'This is an lstm', 0)
  2. writer.add_text('rnn', 'This is an rnn', 10)

  1. add_graph(model, input_to_model=None, verbose=False)?

  1. add_embedding(mat, metadata=None, label_img=None, global_step=None, tag='default', metadata_header=None)?

將嵌入的投影儀數(shù)據(jù)添加到摘要中。

Parameters

  • (torch張量 numpy.array )–矩陣,每行是特征向量 數(shù)據(jù)點(diǎn)
  • 元數(shù)據(jù)(列表)–標(biāo)簽列表,每個元素將轉(zhuǎn)換為字符串
  • label_img (炬管張緊器)–圖像對應(yīng)于每個數(shù)據(jù)點(diǎn)
  • global_step (python:int) – Global step value to record
  • 標(biāo)簽(字符串)–嵌入的名稱

  1. Shape:

墊子:img,其中 N 是數(shù)據(jù)數(shù)量,D 是特征尺寸

label_img:img

Examples:

  1. import keyword
  2. import torch
  3. meta = []
  4. while len(meta)<100:
  5. meta = meta+keyword.kwlist # get some strings
  6. meta = meta[:100]
  7. for i, v in enumerate(meta):
  8. meta[i] = v+str(i)
  9. label_img = torch.rand(100, 3, 10, 32)
  10. for i in range(100):
  11. label_img[i]*=i/100.0
  12. writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img)
  13. writer.add_embedding(torch.randn(100, 5), label_img=label_img)
  14. writer.add_embedding(torch.randn(100, 5), metadata=meta)

  1. add_pr_curve(tag, labels, predictions, global_step=None, num_thresholds=127, weights=None, walltime=None)?

添加精度召回曲線。 繪制精確召回曲線可以讓您了解模型在不同閾值設(shè)置下的性能。 使用此功能,您可以為每個目標(biāo)提供地面真相標(biāo)簽(T / F)和預(yù)測置信度(通常是模型的輸出)。 TensorBoard UI 將允許您交互選擇閾值。

Parameters

  • tag (string) – Data identifier
  • 標(biāo)簽 (torch張量 , numpy.array 字符串/名稱)–基本事實(shí)數(shù)據(jù)。 每個元素的二進(jìn)制標(biāo)簽。
  • 預(yù)測 (torch張量 , numpy.array string / blobname )–元素歸類為 true 的概率。 值應(yīng)為[0,1]
  • global_step (python:int) – Global step value to record
  • num_thresholds (python:int )–用于繪制曲線的閾值數(shù)。
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. import numpy as np
  3. labels = np.random.randint(2, size=100) # binary label
  4. predictions = np.random.rand(100)
  5. writer = SummaryWriter()
  6. writer.add_pr_curve('pr_curve', labels, predictions, 0)
  7. writer.close()

  1. add_custom_scalars(layout)?

通過在“標(biāo)量”中收集圖表標(biāo)簽來創(chuàng)建特殊圖表。 請注意,該函數(shù)只能為每個 SummaryWriter()對象調(diào)用一次。 因?yàn)樗鼉H向張量板提供元數(shù)據(jù),所以可以在訓(xùn)練循環(huán)之前或之后調(diào)用該函數(shù)。

Parameters

布局 (dict )– {類別名稱:圖表},其中圖表也是字典{chartName: ListOfProperties ]}。 ListOfProperties 中的第一個元素是圖表的類型(多線保證金之一),第二個元素應(yīng)是包含您在 add_scalar 中使用的標(biāo)簽的列表。 函數(shù),它將被收集到新圖表中。

Examples:

  1. layout = {'Taiwan':{'twse':['Multiline',['twse/0050', 'twse/2330']]},
  2. 'USA':{ 'dow':['Margin', ['dow/aaa', 'dow/bbb', 'dow/ccc']],
  3. 'nasdaq':['Margin', ['nasdaq/aaa', 'nasdaq/bbb', 'nasdaq/ccc']]}}
  4. writer.add_custom_scalars(layout)

  1. add_mesh(tag, vertices, colors=None, faces=None, config_dict=None, global_step=None, walltime=None)?

將網(wǎng)格或 3D 點(diǎn)云添加到 TensorBoard。 可視化基于 Three.js,因此它允許用戶與渲染的對象進(jìn)行交互。 除了頂點(diǎn),面部之類的基本定義外,用戶還可以提供相機(jī)參數(shù),光照條件等。請檢查 https://threejs.org/docs/index.html#manual/en/introduction/Creating-a -scene 用于高級用法。

Parameters

  • tag (string) – Data identifier
  • 頂點(diǎn) (torch張量)–頂點(diǎn)的 3D 坐標(biāo)列表。
  • 顏色 (torch張量)–每個頂點(diǎn)的顏色
  • (torch張量)–每個三角形內(nèi)的頂點(diǎn)的索引。 (可選的)
  • config_dict –具有 ThreeJS 類名稱和配置的字典。
  • global_step (python:int) – Global step value to record
  • walltime (python:float) – Optional override default walltime (time.time()) seconds after epoch of event

  1. Shape:

頂點(diǎn):img。 (批次,頂點(diǎn)數(shù),渠道)

顏色:img。 對于 <cite>uint8</cite> 類型,值應(yīng)位于[0,255]中;對于 <cite>float</cite> 類型,值應(yīng)位于[0,1]中。

面孔:img。 對于 <cite>uint8</cite> 類型,這些值應(yīng)位于[0,number_of_vertices]中。

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. vertices_tensor = torch.as_tensor([
  3. [1, 1, 1],
  4. [-1, -1, 1],
  5. [1, -1, -1],
  6. [-1, 1, -1],
  7. ], dtype=torch.float).unsqueeze(0)
  8. colors_tensor = torch.as_tensor([
  9. [255, 0, 0],
  10. [0, 255, 0],
  11. [0, 0, 255],
  12. [255, 0, 255],
  13. ], dtype=torch.int).unsqueeze(0)
  14. faces_tensor = torch.as_tensor([
  15. [0, 2, 3],
  16. [0, 3, 1],
  17. [0, 1, 2],
  18. [1, 3, 2],
  19. ], dtype=torch.int).unsqueeze(0)
  20. writer = SummaryWriter()
  21. writer.add_mesh('my_mesh', vertices=vertices_tensor, colors=colors_tensor, faces=faces_tensor)
  22. writer.close()

  1. add_hparams(hparam_dict=None, metric_dict=None)?

添加一組要在 TensorBoard 中進(jìn)行比較的超參數(shù)。

Parameters

  • hparam_dict (dict )–字典中的每個鍵值對都是超參數(shù)的名稱及其對應(yīng)的值。
  • metric_dict (dict )–詞典中的每個鍵值對都是指標(biāo)的名稱及其對應(yīng)的值。 請注意,此處使用的密鑰在張量板記錄中應(yīng)該是唯一的。 否則,由add_scalar添加的值將顯示在 hparam 插件中。 在大多數(shù)情況下,這是不需要的。

Examples:

  1. from torch.utils.tensorboard import SummaryWriter
  2. with SummaryWriter() as w:
  3. for i in range(5):
  4. w.add_hparams({'lr': 0.1*i, 'bsize': i},
  5. {'hparam/accuracy': 10*i, 'hparam/loss': 10*i})

Expected result:

_images/add_hparam.png

  1. flush()?

將事件文件刷新到磁盤。 調(diào)用此方法以確保所有未決事件均已寫入磁盤。

  1. close()?
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號