pytorch 中Tensor.new()的使用

pytorch 中Tensor.new()的使用

一、作用

创建一个新的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_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添加噪声,添加如下代码即可实现:

noise = inputs.data.new(inputs.size()).normal_(0,0.01)
print(noise)

结果如下:

tensor([ 0.0062, 0.0137, -0.0209, 0.0072], device='cuda:0')
  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值