Pytorch中.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)用(添加噪聲)
可以對(duì)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')
以上這篇Pytorch中.new()的作用詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)Tab自動(dòng)補(bǔ)全和歷史命令管理的方法
這篇文章主要介紹了Python實(shí)現(xiàn)Tab自動(dòng)補(bǔ)全和歷史命令管理的方法,實(shí)例分析了tab自動(dòng)補(bǔ)全的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03
Python實(shí)現(xiàn)準(zhǔn)確獲取PDF文件中的標(biāo)題
想要在PDF文件中,解析獲取全部的標(biāo)題,是一件比較麻煩的事情,這篇文章將介紹一種較為準(zhǔn)確的提取標(biāo)題的方式,感興趣的小伙伴可以了解一下2024-02-02
關(guān)于python的編碼與解碼decode()方法及zip()函數(shù)
這篇文章主要介紹了關(guān)于python的編碼與解碼decode()方法及zip()函數(shù),encode0?方法是字符串對(duì)象內(nèi)置的一個(gè)實(shí)現(xiàn)方法用于實(shí)現(xiàn)編碼操作,需要的朋友可以參考下2023-04-04
Python中urllib與urllib2模塊的變化與使用詳解
urllib是python提供的一個(gè)用于操作URL的模塊,在python2.x中有URllib庫,也有Urllib2庫,在python3.x中Urllib2合并到了Urllib中,我們爬取網(wǎng)頁的時(shí)候需要經(jīng)常使用到這個(gè)庫,需要的朋友可以參考下2023-05-05

