import torch
x1 = torch.ones(2, 2)
print(x1)
# tensor([[1., 1.],
# [1., 1.]])
x2 = torch.ones(2, 2, requires_grad = True)
print(x2)
# tensor([[1., 1.],
# [1., 1.]], requires_grad=True)
import torch
x1 = torch.ones(2, 2)
print(x1)
# tensor([[1., 1.],
# [1., 1.]])
y1 = x1 + 2
print(y1)
# tensor([[3., 3.],
# [3., 3.]])
x2 = torch.ones(2, 2, requires_grad=True)
print(x2)
# tensor([[1., 1.],
# [1., 1.]], requires_grad=True)
y2 = x2 + 2
print(y2)
# tensor([[3., 3.],
# [3., 3.]], grad_fn=<AddBackward0>)
<AddBackward0>인 것을 확인할 수 있음import torch
x = torch.ones(2, 2, requires_grad=True)
y1 = x + 2
print(y1)
# tensor([[3., 3.],
# [3., 3.]], grad_fn=<AddBackward0>)
y2 = x - 2
print(y2)
# tensor([[-1., -1.],
# [-1., -1.]], grad_fn=<SubBackward0>)
y3 = x * 2
print(y3)
# tensor([[2., 2.],
# [2., 2.]], grad_fn=<MulBackward0>)
y4 = x / 2
print(y4)
# tensor([[0.5000, 0.5000],
# [0.5000, 0.5000]], grad_fn=<DivBackward0>)
x = torch.ones(2, 2)
y = x + 2
print(x)
# tensor([[1., 1.],
# [1., 1.]])
print(y)
# tensor([[3., 3.],
# [3., 3.]])
y.requires_grad_(True)
print(x)
# tensor([[1., 1.],
# [1., 1.]])
print(y)
# tensor([[3., 3.],
# [3., 3.]], requires_grad=True)
다음 식을 x에 대하여 미분한다고 가정:
이 때 도함수 를 구하면 지점의 경사를 구할 수 있음
x = torch.tensor(2.0, requires_grad=True)
y = 9*x**4 + 2*x**3 + 3*x**2 + 6*x + 1
y.backward()
print(x.grad)
# tensor(330.)
X=[1.0,2.0;3.0,4.0]이라고도 쓰는 듯)x = torch.tensor([[1.0, 2.0],[3.0, 4.0]], requires_grad = True)
# tensor([[1., 2.],
# [3., 4.]], requires_grad=True)
y = x + 2
# tensor([[3., 4.],
# [5., 6.]], grad_fn=<AddBackward0>)
z = y * y * 3
# tensor([[ 27., 48.],
# [ 75., 108.]], grad_fn=<MulBackward0>)
out = z.mean()
# tensor(64.5000, grad_fn=<MeanBackward0>)
out.backward()
print(x.grad)
# tensor([[4.5000, 6.0000],
# [7.5000, 9.0000]])
x = torch.randn(2, 2, requires_grad=True)
y = x + 2
z = (y * y)
y.backward(z)
print(x.grad)
# tensor([[2.2796, 3.2123],
# [5.1224, 0.6321]])
print(y.grad)
# None
print(z.grad)
# None
x = torch.tensor(1.0, requires_grad=True)
z = torch.tensor(2.0, requires_grad=True)
y = x**2 + z**3
y.backward()
print(x.grad, z.grad)
## tensor(2.) tensor(12.)
x = torch.tensor(1.0, requires_grad = True)
print(x.requires_grad)
# True
with torch.no_grad():
print(x.requires_grad)
print((x**2).requires_grad)
# True
# False
print(x.requires_grad)
# True