pytorch中Tensor.new()的使用解析
一、作用
創(chuàng)建一個新的Tensor,該Tensor的 type 和 device 都和原有Tensor一致,且無內(nèi)容。
二、使用方法
如果隨機(jī)定義一個大小的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)文章
Python函數(shù)調(diào)用的幾種方式(類里面,類之間,類外面)
本文主要介紹了Python函數(shù)調(diào)用的幾種方式(類里面,類之間,類外面),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
Python的Flask框架中Flask-Admin庫的簡單入門指引
這篇文章主要介紹了一個Python的Flask框架中Flask-Admin庫簡單入門的指引,包括介紹和簡單的部署等,需要的朋友可以參考下2015-04-04
python利用多種方式來統(tǒng)計(jì)詞頻(單詞個數(shù))
這篇文章主要介紹了python利用多種方式來統(tǒng)計(jì)詞頻(單詞個數(shù)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05
使用Python神器對付12306變態(tài)驗(yàn)證碼
這篇文章主要介紹了使用Python神器對付12306變態(tài)驗(yàn)證碼的相關(guān)資料,需要的朋友可以參考下2016-01-01
Python操作mongodb數(shù)據(jù)庫的方法詳解
這篇文章主要介紹了Python操作mongodb數(shù)據(jù)庫的方法,結(jié)合實(shí)例形式詳細(xì)分析了Python下載、安裝pymongo及操作MongoDB數(shù)據(jù)庫相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-12-12
Windows10+anacond+GPU+pytorch安裝詳細(xì)過程
這篇文章主要介紹了Windows10+anacond+GPU+pytorch安裝詳細(xì)過程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03

