最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Pytorch四維Tensor轉(zhuǎn)圖片并保存方式(維度順序調(diào)整)

 更新時(shí)間:2022年12月13日 10:43:30   作者:'楓  
這篇文章主要介紹了Pytorch四維Tensor轉(zhuǎn)圖片并保存方式(維度順序調(diào)整),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Pytorch四維Tensor轉(zhuǎn)圖片并保存

最近在復(fù)現(xiàn)一篇論文代碼的過程中,想要輸出中間圖片的結(jié)果圖,通過debug發(fā)現(xiàn)在pytorch網(wǎng)絡(luò)中是用Tensor存儲的四維張量。

在這里插入圖片描述

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é)果,并存儲到磁盤中

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í)間命名存儲結(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ì)算絕對值并返回修改后的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).要創(chuàng)建具有特定大小的tensor,使用torch.*,如torch.rand()。

(3).要創(chuàng)建與另一個(gè)tensor具有相同大小(和相似類型)的tensor,使用torch.*_like,如torch.rand_like()。

(4).要創(chuàng)建與另一個(gè)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記錄對它們的操作以進(jìn)行自動微分
    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: # 張量運(yùn)算: 有超過100種張量相關(guān)的運(yùn)算操作,例如轉(zhuǎn)置、索引、切片、數(shù)學(xué)運(yùn)算、線性代數(shù)、隨機(jī)采樣等
    # 所有這些運(yùn)算都可以在GPU上運(yùn)行(相對于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.自動賦值運(yùn)算: 通常在方法后有"_"作為后綴,例如: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ū)域,改變其中一個(gè)另一個(gè)也會隨之改變
    # 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é)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

南陵县| 台安县| 山阴县| 临沧市| 确山县| 双江| 广东省| 治多县| 宝丰县| 荥经县| 东光县| 沛县| 廉江市| 和硕县| 高碑店市| 德令哈市| 增城市| 肥西县| 黑山县| 巴中市| 长汀县| 宁阳县| 武宁县| 铜鼓县| 东乌珠穆沁旗| 阳高县| 留坝县| 丹棱县| 四川省| 封丘县| 巴林左旗| 和顺县| 沂水县| 纳雍县| 星子县| 廉江市| 凌云县| 通许县| 格尔木市| 耿马| 吉木乃县|