30 lines
455 B
Python
30 lines
455 B
Python
|
#!/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)
|