欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Pytorch中.new()的作用详解

时间:2021-05-09 07:44:21|栏目:Python代码|点击:

一、作用

创建一个新的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')

上一篇:更换Django默认的模板引擎为jinja2的实现方法

栏    目:Python代码

下一篇:python使用reportlab实现图片转换成pdf的方法

本文标题:Pytorch中.new()的作用详解

本文地址:http://www.codeinn.net/misctech/117823.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有