Pytorch四維Tensor轉(zhuǎn)圖片并保存方式(維度順序調(diào)整)
Pytorch四維Tensor轉(zhuǎn)圖片并保存
最近在復(fù)現(xiàn)一篇論文代碼的過程中,想要輸出中間圖片的結(jié)果圖,通過debug發(fā)現(xiàn)在pytorch網(wǎng)絡(luò)中是用Tensor存儲的四維張量。
1.維度順序轉(zhuǎn)換
第一維代表的是batch_size,然后是通道數(shù)和圖像尺寸,首先要進行維度順序的轉(zhuǎn)換
通過permute函數(shù)實現(xiàn)
outputRs = outputR.permute(0,2,3,1)
shape轉(zhuǎn)為96 * 128 * 3
2.轉(zhuǎn)為numpy數(shù)組
#由于代碼中的中間結(jié)果是帶有梯度的要進行detach()操作 k = outputRs.cpu().detach().numpy()
3.根據(jù)第一維度batch_size逐個讀取中間結(jié)果,并存儲到磁盤中
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() #通過時間命名存儲結(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ù),都是使用張量來進行描述。
torch包中定義了10種具有CPU和GPU變體的tensor類型。
torch.Tensor或torch.tensor是一種包含單一數(shù)據(jù)類型元素的多維矩陣。
torch.Tensor或torch.tensor注意事項
(1). torch.Tensor是默認(rèn)tensor類型torch.FloatTensor的別名。
(2). torch.tensor總是拷貝數(shù)據(jù)。
(3).每一個tensor都有一個關(guān)聯(lián)的torch.Storage,它保存著它的數(shù)據(jù)。
(4).改變tensor的方法是使用下劃線后綴標(biāo)記,如torch.FloatTensor.abs_()就地(in-place)計算絕對值并返回修改后的tensor,而torch.FloatTensor.abs()在新tensor中計算結(jié)果。
(5).有幾百種tensor相關(guān)的運算操作,包括各種數(shù)學(xué)運算、線性代數(shù)、隨機采樣等。
創(chuàng)建tensor的四種主要方法
(1).要使用預(yù)先存在的數(shù)據(jù)創(chuàng)建tensor,使用torch.tensor()。
(2).要創(chuàng)建具有特定大小的tensor,使用torch.*,如torch.rand()。
(3).要創(chuàng)建與另一個tensor具有相同大小(和相似類型)的tensor,使用torch.*_like,如torch.rand_like()。
(4).要創(chuàng)建與另一個tensor類型相似但大小不同的tensor,使用tensor.new_*,如tensor.new_ones()。
以上內(nèi)容及以下測試代碼主要參考:
1. torch.Tensor — PyTorch 1.10.0 documentation
2. https://pytorch.apachecn.org/#/docs/1.7/03
tensor具體用法見以下test_tensor.py測試代碼:
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記錄對它們的操作以進行自動微分 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ù)類型以及它們所存儲的設(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)存中存儲 print(f"tensor dim: {tensor.ndim}") # tensor維度 elif var == 3: # 張量運算: 有超過100種張量相關(guān)的運算操作,例如轉(zhuǎn)置、索引、切片、數(shù)學(xué)運算、線性代數(shù)、隨機采樣等 # 所有這些運算都可以在GPU上運行(相對于CPU來說可以達到更高的運算速度) tensor = torch.rand((4, 4), dtype=torch.float); print(f"src: {tensor}") # 判斷當(dāng)前環(huán)境GPU是否可用,然后將tensor導(dǎo)入GPU內(nèi)運行 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方法將一組張量按照指定的維度進行拼接,也可以參考torch.stack方法,但與torch.cat稍微有點不同 cat = torch.cat([tensor, tensor], dim=1); print(f"cat:\n {cat}") # 3.張量的乘積和矩陣乘法 print(f"tensor.mul(tensor):\n {tensor.mul(tensor)}") # 逐個元素相乘結(jié)果 print(f"tensor * tensor:\n {tensor * tensor}") # 等價寫法 print(f"tensor.matmul(tensor.T):\n {tensor.matmul(tensor.T)}") # 張量與張量的矩陣乘法 print(f"tensor @ tensor.T:\n {tensor @ tensor.T}") # 等價寫法 # 4.自動賦值運算: 通常在方法后有"_"作為后綴,例如:x.copy_(y), x.t_()操作會改變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ū)域,改變其中一個另一個也會隨之改變 # 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ù)組值也會隨之改變 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ù)組的值,則張量值也會隨之改變 print(f"n: {n}") print(f"t: {t}") print("test finish")
GitHub:GitHub - fengbingchun/PyTorch_Test: PyTorch's usage
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Windows 下更改 jupyterlab 默認(rèn)啟動位置的教程詳解
這篇文章主要介紹了Windows 下更改 jupyterlab 默認(rèn)啟動位置,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Python3使用requests模塊實現(xiàn)顯示下載進度的方法詳解
這篇文章主要介紹了Python3使用requests模塊實現(xiàn)顯示下載進度的方法,結(jié)合實例形式分析了Python3中requests模塊的配置、使用及顯示進度條類的相關(guān)定義方法,需要的朋友可以參考下2019-02-02python調(diào)用百度REST API實現(xiàn)語音識別
這篇文章主要為大家詳細介紹了python調(diào)用百度REST API實現(xiàn)語音識別,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08Python利用pandas對數(shù)據(jù)進行特定排序
本文主要介紹了Python利用pandas對數(shù)據(jù)進行特定排序,主要使用?pandas.DataFrame.sort_values?方法,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-03-03