Pytorch中.new()的作用詳解
一、作用
創(chuàng)建一個新的Tensor,該Tensor的type和device都和原有Tensor一致,且無內容。
二、使用方法
如果隨機定義一個大小的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)
結果如下:
可以看到不論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
四、實際應用(添加噪聲)
可以對Tensor添加噪聲,添加如下代碼即可實現(xiàn):
noise = inputs.data.new(inputs.size()).normal_(0,0.01) print(noise)
結果如下:
tensor([ 0.0062, 0.0137, -0.0209, 0.0072], device='cuda:0')
以上這篇Pytorch中.new()的作用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python 在OpenCV里實現(xiàn)仿射變換—坐標變換效果
這篇文章主要介紹了Python 在OpenCV里實現(xiàn)仿射變換—坐標變換效果,本文通過一個例子給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08
詳解python如何根據(jù)參數(shù)不同調用不同的類和方法
這篇文章主要為大家詳細介紹了在python中如何根據(jù)參數(shù)不同調用不同的類和方法,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-03-03
Python+tkinter實現(xiàn)制作文章搜索軟件
無聊的時候做了一個搜索文章的軟件,有沒有更加的方便快捷不知道,好玩就行了。軟件是利用Python和tkinter實現(xiàn)的,感興趣的可以嘗試一下2022-10-10

