让我们逐步分解以更好地理解代码。
以下代码块创建了一个形状为(1,3)的张量
x。
x = torch.ones(3, requires_grad=True)
print(x)
>>> tensor([1., 1., 1.], requires_grad=True)
以下代码块通过将
x的每个元素乘以2来创建张量
y。
y = x * 2
print(y)
print(y.requires_grad)
>>> tensor([2., 2., 2.], grad_fn=<MulBackward0>)
>>> True
TORCH.data返回一个张量,其requires_grad被设置为false
print(y.data)
print('Type of y: ', type(y.data))
print('requires_grad: ', y.data.requires_grad)
>>> tensor([2., 2., 2.])
>>> Type of y: <class 'torch.Tensor'>
>>> requires_grad: False
TORCH.norm() 返回给定张量的矩阵范数或向量范数。默认情况下,它返回一个Frobenius范数,也称为L2范数,其使用以下公式计算:
。
在我们的示例中,由于y中的每个元素都是2,因此y.data.norm()返回3.4641,因为
等于3.4641
print(y.data.norm())
>>> tensor(3.4641)
以下循环将一直运行,直到范数小于1000。
while y.data.norm() < 1000:
print('Norm value: ', y.data.norm(), 'y value: ', y.data )
y = y * 2
>>> Norm value: tensor(6.9282) y value: tensor([4., 4., 4.])
>>> Norm value: tensor(3.4641) y value: tensor([2., 2., 2.])
>>> Norm value: tensor(13.8564) y value: tensor([8., 8., 8.])
>>> Norm value: tensor(27.7128) y value: tensor([16., 16., 16.])
>>> Norm value: tensor(55.4256) y value: tensor([32., 32., 32.])
>>> Norm value: tensor(110.8512) y value: tensor([64., 64., 64.])
>>> Norm value: tensor(221.7025) y value: tensor([128., 128., 128.])
>>> Norm value: tensor(443.4050) y value: tensor([256., 256., 256.])
>>> Norm value: tensor(886.8100) y value: tensor([512., 512., 512.])
>>>
>>> Final y value: tensor([1024., 1024., 1024.], grad_fn=<MulBackward0>)