torch基础学习二
In [1]:
import torch
In [2]:
# 初始化值x
x = torch.randn(3,4,requires_grad=True)
x
Out[2]:
tensor([[ 0.0687, 1.3774, -0.6309, 1.8103], [-0.1166, 0.6219, -1.0023, -1.0381], [-0.5388, 0.3428, -1.5833, -1.7233]], requires_grad=True)
In [3]:
# 初始化值X
x = torch.randn(3,4)
x.requires_grad=True
x
Out[3]:
tensor([[ 0.7752, 2.3479, 0.2382, 1.6564], [ 0.1899, -0.4560, -0.5426, 0.0801], [-0.6984, 1.5270, -0.2892, 1.4730]], requires_grad=True)
In [4]:
# 初始化值b
b = torch.randn(3,4,requires_grad=True)
b
Out[4]:
tensor([[-0.4051, -1.1639, 1.3656, -2.5245], [-0.7276, 1.4965, -1.2357, -0.4508], [-0.3058, -0.1797, 0.0175, -1.6981]], requires_grad=True)
In [5]:
# 求和
t = x + b
y = t.sum()
y
Out[5]:
tensor(0.4901, grad_fn=<SumBackward0>)
In [6]:
y.backward()
In [7]:
b.grad
Out[7]:
tensor([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]])
In [8]:
x.requires_grad,b.requires_grad,t.requires_grad
Out[8]:
(True, True, True)