Pytorch四維Tensor轉(zhuǎn)圖片并保存方式(維度順序調(diào)整)
Pytorch四維Tensor轉(zhuǎn)圖片并保存
最近在復(fù)現(xiàn)一篇論文代碼的過程中,想要輸出中間圖片的結(jié)果圖,通過debug發(fā)現(xiàn)在pytorch網(wǎng)絡(luò)中是用Tensor存儲(chǔ)的四維張量。
1.維度順序轉(zhuǎn)換
第一維代表的是batch_size,然后是通道數(shù)和圖像尺寸,首先要進(jìn)行維度順序的轉(zhuǎn)換
通過permute函數(shù)實(shí)現(xiàn)
outputRs = outputR.permute(0,2,3,1)
shape轉(zhuǎn)為96 * 128 * 3
2.轉(zhuǎn)為numpy數(shù)組
#由于代碼中的中間結(jié)果是帶有梯度的要進(jìn)行detach()操作 k = outputRs.cpu().detach().numpy()
3.根據(jù)第一維度batch_size逐個(gè)讀取中間結(jié)果,并存儲(chǔ)到磁盤中
Image需導(dǎo)入from PIL import Image
for i in range(10): res = k[i] #得到batch中其中一步的圖片 image = Image.fromarray(np.uint8(res)).convert('RGB') #image.show() #通過時(shí)間命名存儲(chǔ)結(jié)果 timestamp = datetime.datetime.now().strftime("%M-%S") savepath = timestamp + '_r.jpg' image.save(savepath)
Pytorch中Tensor介紹
PyTorch中的張量(Tensor)如同數(shù)組和矩陣一樣,是一種特殊的數(shù)據(jù)結(jié)構(gòu)。在PyTorch中,神經(jīng)網(wǎng)絡(luò)的輸入、輸出以及網(wǎng)絡(luò)的參數(shù)等數(shù)據(jù),都是使用張量來進(jìn)行描述。
torch包中定義了10種具有CPU和GPU變體的tensor類型。
torch.Tensor或torch.tensor是一種包含單一數(shù)據(jù)類型元素的多維矩陣。
torch.Tensor或torch.tensor注意事項(xiàng)
(1). torch.Tensor是默認(rèn)tensor類型torch.FloatTensor的別名。
(2). torch.tensor總是拷貝數(shù)據(jù)。
(3).每一個(gè)tensor都有一個(gè)關(guān)聯(lián)的torch.Storage,它保存著它的數(shù)據(jù)。
(4).改變tensor的方法是使用下劃線后綴標(biāo)記,如torch.FloatTensor.abs_()就地(in-place)計(jì)算絕對(duì)值并返回修改后的tensor,而torch.FloatTensor.abs()在新tensor中計(jì)算結(jié)果。
(5).有幾百種tensor相關(guān)的運(yùn)算操作,包括各種數(shù)學(xué)運(yùn)算、線性代數(shù)、隨機(jī)采樣等。
創(chuàng)建tensor的四種主要方法
(1).要使用預(yù)先存在的數(shù)據(jù)創(chuàng)建tensor,使用torch.tensor()。
(2).要?jiǎng)?chuàng)建具有特定大小的tensor,使用torch.*,如torch.rand()。
(3).要?jiǎng)?chuàng)建與另一個(gè)tensor具有相同大小(和相似類型)的tensor,使用torch.*_like,如torch.rand_like()。
(4).要?jiǎng)?chuàng)建與另一個(gè)tensor類型相似但大小不同的tensor,使用tensor.new_*,如tensor.new_ones()。
以上內(nèi)容及以下測(cè)試代碼主要參考:
1. torch.Tensor — PyTorch 1.10.0 documentation
2. https://pytorch.apachecn.org/#/docs/1.7/03
tensor具體用法見以下test_tensor.py測(cè)試代碼:
import torch import numpy as np var = 2 # reference: https://pytorch.apachecn.org/#/docs/1.7/03 if var == 1: # 張量初始化 # 1.直接生成張量, 注意: torch.tensor與torch.Tensor的區(qū)別: torch.Tensor是torch.FloatTensor的別名;而torch.tensor則根據(jù)輸入數(shù)據(jù)推斷數(shù)據(jù)類型 data = [[1, 2], [3, 4]] x_data = torch.tensor(data); print(f"x_data: {x_data}, type: {x_data.type()}") # type: torch.LongTensor y_data = torch.Tensor(data); print(f"y_data: {y_data}, type: {y_data.type()}") # type: torch.FloatTensor z_data = torch.IntTensor(data); print(f"z_data: {z_data}, type: {z_data.type()}") # type: torch.IntTensor # 2.通過Numpy數(shù)組來生成張量,反過來也可以由張量生成Numpy數(shù)組 np_array = np.array(data) x_np = torch.from_numpy(np_array); print("x_np:\n", x_np) y_np = torch.tensor(np_array); print("y_np:\n", y_np) # torch.tensor總是拷貝數(shù)據(jù) z_np = torch.as_tensor(np_array); print("z_np:\n", z_np) # 使用torch.as_tensor可避免拷貝數(shù)據(jù) # 3.通過已有的張量來生成新的張量: 新的張量將繼承已有張量的屬性(結(jié)構(gòu)、類型),也可以重新指定新的數(shù)據(jù)類型 x_ones = torch.ones_like(x_data); print(f"x_ones: {x_ones}, type: {x_ones.type()}") # 保留x_data的屬性 x_rand = torch.rand_like(x_data, dtype=torch.float); print(f"x_rand: {x_rand}, type: {x_rand.type()}") # 重寫x_data的數(shù)據(jù)類型: long -> float tensor = torch.tensor((), dtype=torch.int32); print(f"shape of tensor: {tensor.shape}, type: {tensor.type()}") new_tensor = tensor.new_ones((2, 3)); print(f"shape of new_tensor: {new_tensor.shape}, type: {new_tensor.type()}") # 4.通過指定數(shù)據(jù)維度來生成張量 shape = (2, 3) # shape是元組類型,用來描述張量的維數(shù) rand_tensor = torch.rand(shape); print(f"rand_tensor: {rand_tensor}, type: {rand_tensor.type()}") ones_tensor = torch.ones(shape, dtype=torch.int); print(f"ones_tensor: {ones_tensor}, type: {ones_tensor.type()}") zeros_tensor = torch.zeros(shape, device=torch.device("cpu")); print("zeros_tensor:", zeros_tensor) # 5.可以使用requires_grad=True創(chuàng)建張量,以便torch.autograd記錄對(duì)它們的操作以進(jìn)行自動(dòng)微分 x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True) out = x.pow(2).sum(); print(f"out: {out}") # out.backward(); print(f"x: {x}\nx.grad: {x.grad}") elif var == 2: # 張量屬性: 從張量屬性我們可以得到張量的維數(shù)、數(shù)據(jù)類型以及它們所存儲(chǔ)的設(shè)備(CPU或GPU) tensor = torch.rand(3, 4) print(f"shape of tensor: {tensor.shape}") print(f"datatype of tensor: {tensor.dtype}") # torch.float32 print(f"device tensor is stored on: {tensor.device}") # cpu或cuda print(f"tensor layout: {tensor.layout}") # tensor如何在內(nèi)存中存儲(chǔ) print(f"tensor dim: {tensor.ndim}") # tensor維度 elif var == 3: # 張量運(yùn)算: 有超過100種張量相關(guān)的運(yùn)算操作,例如轉(zhuǎn)置、索引、切片、數(shù)學(xué)運(yùn)算、線性代數(shù)、隨機(jī)采樣等 # 所有這些運(yùn)算都可以在GPU上運(yùn)行(相對(duì)于CPU來說可以達(dá)到更高的運(yùn)算速度) tensor = torch.rand((4, 4), dtype=torch.float); print(f"src: {tensor}") # 判斷當(dāng)前環(huán)境GPU是否可用,然后將tensor導(dǎo)入GPU內(nèi)運(yùn)行 if torch.cuda.is_available(): tensor = tensor.to("cuda") # 1.張量的索引和切片 tensor[:, 1] = 0; print(f"index: {tensor}") # 將第1列(從0開始)的數(shù)據(jù)全部賦值為0 # 2.張量的拼接: 可以通過torch.cat方法將一組張量按照指定的維度進(jìn)行拼接,也可以參考torch.stack方法,但與torch.cat稍微有點(diǎn)不同 cat = torch.cat([tensor, tensor], dim=1); print(f"cat:\n {cat}") # 3.張量的乘積和矩陣乘法 print(f"tensor.mul(tensor):\n {tensor.mul(tensor)}") # 逐個(gè)元素相乘結(jié)果 print(f"tensor * tensor:\n {tensor * tensor}") # 等價(jià)寫法 print(f"tensor.matmul(tensor.T):\n {tensor.matmul(tensor.T)}") # 張量與張量的矩陣乘法 print(f"tensor @ tensor.T:\n {tensor @ tensor.T}") # 等價(jià)寫法 # 4.自動(dòng)賦值運(yùn)算: 通常在方法后有"_"作為后綴,例如:x.copy_(y), x.t_()操作會(huì)改變x的取值(in-place) print(f"tensor:\n {tensor}") print(f"tensor:\n {tensor.add_(5)}") elif var == 4: # Tensor與Numpy的轉(zhuǎn)化: 張量和Numpy array數(shù)組在CPU上可以共用一塊內(nèi)存區(qū)域,改變其中一個(gè)另一個(gè)也會(huì)隨之改變 # 1.由張量變換為Numpy array數(shù)組 t = torch.ones(5); print(f"t: {t}") n = t.numpy(); print(f"n: {n}") t.add_(1) # 修改張量的值,則Numpy array數(shù)組值也會(huì)隨之改變 print(f"t: {t}") print(f"n: {n}") # 2.由Numpy array數(shù)組轉(zhuǎn)為張量 n = np.ones(5); print(f"n: {n}") t = torch.from_numpy(n); print(f"t: {t}") np.add(n, 1, out=n) # 修改Numpy array數(shù)組的值,則張量值也會(huì)隨之改變 print(f"n: {n}") print(f"t: {t}") print("test finish")
GitHub:GitHub - fengbingchun/PyTorch_Test: PyTorch's usage
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django異步任務(wù)線程池實(shí)現(xiàn)原理
這篇文章主要介紹了Django異步任務(wù)線程池實(shí)現(xiàn)原理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12如何利用itertuples對(duì)DataFrame進(jìn)行遍歷
這篇文章主要介紹了如何利用itertuples對(duì)DataFrame進(jìn)行遍歷問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06Windows 下更改 jupyterlab 默認(rèn)啟動(dòng)位置的教程詳解
這篇文章主要介紹了Windows 下更改 jupyterlab 默認(rèn)啟動(dòng)位置,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05Python3使用requests模塊實(shí)現(xiàn)顯示下載進(jìn)度的方法詳解
這篇文章主要介紹了Python3使用requests模塊實(shí)現(xiàn)顯示下載進(jìn)度的方法,結(jié)合實(shí)例形式分析了Python3中requests模塊的配置、使用及顯示進(jìn)度條類的相關(guān)定義方法,需要的朋友可以參考下2019-02-02python調(diào)用百度REST API實(shí)現(xiàn)語(yǔ)音識(shí)別
這篇文章主要為大家詳細(xì)介紹了python調(diào)用百度REST API實(shí)現(xiàn)語(yǔ)音識(shí)別,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08Python利用pandas對(duì)數(shù)據(jù)進(jìn)行特定排序
本文主要介紹了Python利用pandas對(duì)數(shù)據(jù)進(jìn)行特定排序,主要使用?pandas.DataFrame.sort_values?方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-03-03Python自然語(yǔ)言處理停用詞過濾實(shí)例詳解
這篇文章主要為大家介紹了Python自然語(yǔ)言處理停用詞過濾實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01深入理解Python虛擬機(jī)中常見魔術(shù)方法的使用
本文主要給大家介紹在 python 當(dāng)中與數(shù)學(xué)計(jì)算相關(guān)的一些常見的魔術(shù)方法,是在很多科學(xué)計(jì)算的包當(dāng)中都使用到的魔術(shù)方法,感興趣的小伙伴可以了解一下2023-05-05Python使用樹狀圖實(shí)現(xiàn)可視化聚類詳解
一般情況下,我們都是使用散點(diǎn)圖進(jìn)行聚類可視化,但是某些的聚類算法可視化時(shí)散點(diǎn)圖并不理想,所以在這篇文章中,我們介紹如何使用樹狀圖(Dendrograms)對(duì)我們的聚類結(jié)果進(jìn)行可視化2023-03-03