溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Pytorch中.new()的作用詳解

發(fā)布時(shí)間:2020-10-05 10:18:30 來(lái)源:腳本之家 閱讀:249 作者:悲戀花丶無(wú)心之人 欄目:開(kāi)發(fā)技術(shù)

一、作用

創(chuàng)建一個(gè)新的Tensor,該Tensor的typedevice都和原有Tensor一致,且無(wú)內(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_inputstypedevice都與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è)參考,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI