温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pytorch中.new()的作用详解

发布时间:2020-10-05 10:18:30 来源:脚本之家 阅读:235 作者:悲恋花丶无心之人 栏目:开发技术

一、作用

创建一个新的Tensor,该Tensor的typedevice都和原有Tensor一致,且无内容。

二、使用方法

如果随机定义一个大小的Tensor,则新的Tensor有两种创建方法,如下:

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_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

四、实际应用(添加噪声)

可以对Tensor添加噪声,添加如下代码即可实现:

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()的作用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI