# 二、使用方法

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

# 四、实际应用（添加噪声）

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

tensor([ 0.0062,  0.0137, -0.0209,  0.0072], device='cuda:0')

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客