tau-2020-pytorch-tutorial/pytorch2.py

30 lines
455 B
Python
Raw Normal View History

2020-12-09 10:12:35 +01:00
#!/usr/bin/python3
import torch
m = torch.tensor([[2., 1.], [-1., 2.]])
def fun(x):
return m @ x
def loss(y):
return torch.sum((y - torch.tensor([3., 2.]))**2)
x = torch.rand(2, requires_grad=True)
learning_rate = torch.tensor(0.01)
for _ in range(100):
y = fun(x)
cost = loss(y)
print(x, " => ", y, " ", cost)
cost.backward()
with torch.no_grad():
x = x - learning_rate * x.grad
x.requires_grad_(True)