三、TensorBoard

一、安裝TensorBoard

管理員身份運行Anaconda Prompt,進入自己的環境環境 conda activate y_pytorchpip 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端口進行打開。
在這里插入圖片描述
點擊該鏈接或者復制鏈接到瀏覽器打開即可
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377598.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377598.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377598.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

IT資產管理系統SQL版

你難道還在用Excel登記IT資產信息嗎&#xff1f; 那你一定要好好考慮如何面對以下問題 1&#xff1a;IT人員需要面對自身部門以下問題用戶申請了資產it部未處理的單還有哪些?庫存里面還有哪些資產?有多少設備在維修?有多少設備已經報廢了?哪些資產低于安全庫存需要采購?使…

詳細講解設計跳表的三個步驟(查找、插入、刪除)

目錄寫在前面跳表概要查找步驟插入步驟刪除步驟完整代碼寫在前面 關于跳表的一些知識可以參考這篇文章,最好是先看完這篇文章再看詳細的思路->代碼的復現步驟: Redis內部數據結構詳解(6)——skiplist 關于跳表的插入、刪除基本操作其實也就是鏈表的插入和刪除&#xff0c;所…

php 類靜態變量 和 常量消耗內存及時間對比

在對類執行100w次循環后&#xff0c; 常量最快&#xff0c;變量其次&#xff0c;靜態變量消耗時間最高 其中&#xff1a; 常量消耗&#xff1a;101.1739毫秒 變量消耗&#xff1a;2039.7689毫秒 靜態變量消耗&#xff1a;4084.8911毫秒 測試代碼&#xff1a; class Timer_profi…

一個機器周期 計算機_計算機科學組織| 機器周期

一個機器周期 計算機機器周期 (Machine Cycle) The cycle during which a machine language instruction is executed by the processor of the computer system is known as the machine cycle. If a program contains 10 machine language instruction, 10 separate machine …

四、Transforms

transform是torchvision下的一個.py文件&#xff0c;這個python文件中定義了很多的類和方法&#xff0c;主要實現對圖片進行一些變換操作 一、Transforms講解 from torchvision import transforms#按著Ctrl&#xff0c;點擊transforms進入到__init__.py文件中 from .transfo…

leetcode 134. 加油站 思考分析

目錄題目1、暴力法&#xff0c;雙層遍歷2、貪心題目 在一條環路上有 N 個加油站&#xff0c;其中第 i 個加油站有汽油 gas[i] 升。 你有一輛油箱容量無限的的汽車&#xff0c;從第 i 個加油站開往第 i1 個加油站需要消耗汽油 cost[i] 升。你從其中的一個加油站出發&#xff0…

單鏈線性表的實現

//函數結果狀態代碼#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 //Status是函數的類型&#xff0c;其值是函數結果狀態代碼 typedef int Status; typedef int ElemType;…

時間模塊,帶Python示例

Python時間模塊 (Python time Module) The time module is a built-in module in Python and it has various functions that require to perform more operations on time. This is one of the best modules in Python that used to solve various real-life time-related pro…

五、torchvision

一、下載CIFAR-10數據集 CIFAR-10數據集官網 通過閱讀官網給的解釋可以大概了解到&#xff0c;一共6w張圖片&#xff0c;每張圖片大小為3232&#xff0c;5w張訓練圖像&#xff0c;1w張測試圖像&#xff0c;一共由十大類圖像。 CIFAR10官網使用文檔 torchvision.datasets.CIF…

leetcode 69. x 的平方根 思考分析

題目 實現 int sqrt(int x) 函數。 計算并返回 x 的平方根&#xff0c;其中 x 是非負整數。 由于返回類型是整數&#xff0c;結果只保留整數的部分&#xff0c;小數部分將被舍去。 示例 1: 輸入: 4 輸出: 2 示例 2: 輸入: 8 輸出: 2 說明: 8 的平方根是 2.82842…, 由于返回…

背包問題 小灰_小背包問題

背包問題 小灰Prerequisites: Algorithm for fractional knapsack problem 先決條件&#xff1a; 分數背包問題算法 Here, we are discussing the practical implementation of the fractional knapsack problem. It can be solved using the greedy approach and in fraction…

360瀏覽器兼容問題

360瀏覽器兼容問題 360瀏覽器又是一大奇葩&#xff0c;市場份額大&#xff0c;讓我們不得不也對他做些兼容性處理。 360瀏覽器提供了兩種瀏覽模式&#xff0c;極速模式和兼容模式&#xff0c;極速模式下是webkit內核的處理模式&#xff0c;兼容模式下是與IE內核相同的處理模式。…

轉 設計師也需要了解的一些前端知識

一、常見視覺效果是如何實現的 一些事 關于文字效果 互聯網的一些事 文字自身屬性相關的效果css中都是有相對應的樣式的&#xff0c;如字號、行高、加粗、傾斜、下劃線等&#xff0c;但是一些特殊的效果&#xff0c;主要表現為ps中圖層樣式中的效果&#xff0c;css是無能為力的…

六、DataLoader

一、DataLoader參數解析 DataLoader官網使用手冊 參數描述dataset說明數據集所在的位置、數據總數等batch_size每次取多少張圖片shuffleTrue亂序、False順序(默認)samplerbatch_samplernum_workers多進程&#xff0c;默認為0采用主進程加載數據collate_fnpin_memorydrop_las…

單調棧 leetcode整理(一)

目錄單調棧知識402. 移掉K位數字1673. 找出最具競爭力的子序列316. 去除重復字母&#xff08;1081. 不同字符的最小子序列&#xff09;321. 拼接最大數單調棧知識 單調棧就是一個內部元素有序的棧&#xff08;大->小 or 小->大&#xff09;&#xff0c;但是只用到它的一…

數字簽名 那些密碼技術_密碼學中的數字簽名

數字簽名 那些密碼技術A signature is usually used to bind signatory to the message. The digital signature is thus a technique that binds a person or the entity to the digital data. This binding ensures that the person sending the data is solely responsible …

七、torch.nn

一、神經網絡模塊 進入到PyTorch的torch.nnAPI學習頁面 PyTorch提供了很多的神經網絡方面的模塊&#xff0c;NN就是Neural Networks的簡稱 二、Containers torch.nn下的Containers 一共有六個模塊&#xff0c;最常用的就是Module模塊&#xff0c;看解釋可以知道&#xff0c…

Java多線程初學者指南(8):從線程返回數據的兩種方法

本文介紹學習Java多線程中需要學習的從線程返回數據的兩種方法。從線程中返回數據和向線程傳遞數據類似。也可以通過類成員以及回調函數來返回數據。原文鏈接 從線程中返回數據和向線程傳遞數據類似。也可以通過類成員以及回調函數來返回數據。但類成員在返回數據和傳遞數據時有…

【C++進階】 遵循TDD原則,實現平面向量類(Vec2D)

目錄1、明確要實現的類的方法以及成員函數2、假設已經編寫Vec2D&#xff0c;根據要求&#xff0c;寫出測試代碼3、編寫平面向量類Vec2D,并進行測試4、完整代碼5、最終結果1、明確要實現的類的方法以及成員函數 考慮到效率問題&#xff0c;我們一般將函數的參數設置為引用類型。…

Keilc的中斷號計算方法

中斷號碼 (中斷向量-3)/8轉載于:https://www.cnblogs.com/yuqilihualuo/p/3423634.html