Pytorch中.new()的作⽤⽬录
⼀、作⽤
创建⼀个新的Tensor,该Tensor的type和device都和原有Tensor⼀致,且⽆内容。posss
⼆、使⽤⽅法
如果随机定义⼀个⼤⼩的Tensor,则新的Tensor有两种创建⽅法,如下:
inputs = torch.randn(m, n)
new_inputs = w()
new_inputs = w(inputs)四级时间分配
三、具体代码
responsibilityimport torch
rectangle_height = 1
rectangle_width = 4
inputs = torch.randn(rectangle_height, rectangle_width)
for i in range(rectangle_height):
全国大学英语四六级考试(cet)官网
for j in range(rectangle_width):
inputs[i][j] = (i + 1) * (j + 1)
print("inputs:", inputs)
new_inputs = w()
print("new_inputs:", new_inputs)
doubtful# Constructs a new tensor of the same data type as lf tensor.
print(pe(), pe())cuz
print('')
inputs = inputs.squeeze(dim=0)
print("inputs:", inputs)
# new_inputs = w()
new_inputs = w(inputs)
print("new_inputs:", new_inputs)
# Constructs a new tensor of the same data type as lf tensor.
print(pe(), pe())
if torch.cuda.is_available():
cursorlocationdevice = torch.device("cuda")
inputs, new_inputs = (device), (device)
print(inputs.device, new_inputs.device)hbs
结果如下:
可以看到不论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添加噪声,添加如下代码即可实现:
noi = w(inputs.size()).normal_(0,0.01) print(noi)
结果如下:
tensor([ 0.0062, 0.0137, -0.0209, 0.0072], device='cuda:0')