2.5自动微分
(P42)
(base) C:\Users\杨珊>conda activate env_pytorch
(env_pytorch) C:\Users\杨珊>python
Python 3.7.16 (default, Jan 17 2023, 16:06:28) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> x=torch.arange(4)
>>> x
tensor([0, 1, 2, 3])
>>> x.requires_grad_(True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: only Tensors of floating point dtype can require gradients
>>> x=torch.arange(4.0,requires_grad=True)
>>> x.grad
>>> x.grad=4=4*x
File "<stdin>", line 1
SyntaxError: can't assign to literal
>>> y=2*torch.dot(x,x)
>>> y
tensor(28., grad_fn=<MulBackward0>)
>>> y.backward()
>>> x.grad
tensor([ 0., 4., 8., 12.])
>>> x.grad==4*x
tensor([True, True, True, True])
>>> x.grad.zero_()
tensor([0., 0., 0., 0.])
>>> y=x*x
>>> y
tensor([0., 1., 4., 9.], grad_fn=<MulBackward0>)