pytorch中Tensor.new()的使用解析
一、作用
創(chuàng)建一個(gè)新的Tensor,該Tensor的 type 和 device 都和原有Tensor一致,且無內(nèi)容。
二、使用方法
如果隨機(jī)定義一個(gè)大小的Tensor,則新的Tensor有兩種創(chuàng)建方法,如下:
inputs = torch.randn(m, n) new_inputs = inputs.new() new_inputs = torch.Tensor.new(inputs)
三、具體代碼
import torch rectangle_height = 1 rectangle_width = 4 inputs = torch.randn(rectangle_height, rectangle_width) for i in range(rectangle_height): for j in range(rectangle_width): inputs[i][j] = (i + 1) * (j + 1) print("inputs:", inputs) new_inputs = inputs.new() print("new_inputs:", new_inputs) # Constructs a new tensor of the same data type as self tensor. print(new_inputs.type(), inputs.type()) print('') inputs = inputs.squeeze(dim=0) print("inputs:", inputs) # new_inputs = inputs.new() new_inputs = torch.Tensor.new(inputs) print("new_inputs:", new_inputs) # Constructs a new tensor of the same data type as self tensor. print(new_inputs.type(), inputs.type()) if torch.cuda.is_available(): device = torch.device("cuda") inputs, new_inputs = inputs.to(device), new_inputs.to(device) print(inputs.device, new_inputs.device)
結(jié)果如下:
可以看到不論inputs是多少維的,新建的new_inputs的type和device都與inputs保持一致
inputs: tensor([[1., 2., 3., 4.]]) new_inputs: tensor([]) torch.FloatTensor torch.FloatTensor inputs: tensor([1., 2., 3., 4.]) new_inputs: tensor([]) torch.FloatTensor torch.FloatTensor cuda:0 cuda:0
四、實(shí)際應(yīng)用(添加噪聲)
可以對Tensor添加噪聲,添加如下代碼即可實(shí)現(xiàn):
noise = inputs.data.new(inputs.size()).normal_(0,0.01) print(noise)
結(jié)果如下:
tensor([ 0.0062, 0.0137, -0.0209, 0.0072], device='cuda:0')
到此這篇關(guān)于pytorch中Tensor.new()的使用解析的文章就介紹到這了,更多相關(guān)Tensor.new()的使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
tensorflow2.0如何實(shí)現(xiàn)cnn的圖像識(shí)別
這篇文章主要介紹了tensorflow2.0如何實(shí)現(xiàn)cnn的圖像識(shí)別,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12python字典dict中常用內(nèi)置函數(shù)的使用
本文主要介紹了python字典dict中常用內(nèi)置函數(shù)的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04python保留小數(shù)函數(shù)的幾種使用總結(jié)
本文主要介紹了python保留小數(shù)函數(shù)的幾種使用總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02Python實(shí)現(xiàn)內(nèi)存泄露排查的示例詳解
一般在python代碼塊的調(diào)試過程中會(huì)使用memory-profiler、filprofiler、objgraph等三種方式進(jìn)行輔助分析,今天這里主要介紹使用objgraph對象提供的函數(shù)接口來進(jìn)行內(nèi)存泄露的分析,感興趣的可以了解一下2023-01-01Python開發(fā)微信公眾平臺(tái)的方法詳解【基于weixin-knife】
這篇文章主要介紹了Python開發(fā)微信公眾平臺(tái)的方法,結(jié)合實(shí)例形式分析了Python基于weixin-knife針對微信公眾平臺(tái)消息、接口調(diào)用及事件處理的基本操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-07-07