|
!pip install torch |
|
|
|
import torch |
|
|
|
|
|
x1 = torch.tensor([50, 60, 70, 80, 90]) |
|
x2 = torch.tensor([20, 21, 22, 23, 24]) |
|
y_actual = torch.tensor([30, 35, 40, 45, 50]) |
|
|
|
|
|
alpha = 0.01 |
|
max_iters = 1000 |
|
|
|
|
|
Theta0 = torch.tensor(0.0, requires_grad=True) |
|
Theta1 = torch.tensor(0.0, requires_grad=True) |
|
Theta2 = torch.tensor(0.0, requires_grad=True) |
|
|
|
|
|
iter_count = 0 |
|
|
|
|
|
while iter_count < max_iters: |
|
|
|
y_pred = Theta0 + Theta1 * x1 + Theta2 * x2 |
|
|
|
|
|
errors = y_pred - y_actual |
|
|
|
|
|
cost = torch.sum(errors ** 2) / (2 * len(x1)) |
|
|
|
|
|
if iter_count % 100 == 0: |
|
print("Iteration {}: Cost = {}, Theta0 = {}, Theta1 = {}, Theta2 = {}".format(iter_count, cost, Theta0.item(), Theta1.item(), |
|
Theta2.item())) |
|
|
|
|
|
if iter_count > 0 and torch.abs(cost - prev_cost) < 0.0001: |
|
print("Converged after {} iterations".format(iter_count)) |
|
break |
|
|
|
|
|
cost.backward() |
|
|
|
|
|
with torch.no_grad(): |
|
Theta0 -= alpha * Theta0.grad |
|
Theta1 -= alpha * Theta1.grad |
|
Theta2 -= alpha * Theta2.grad |
|
|
|
|
|
Theta0.grad.zero_() |
|
Theta1.grad.zero_() |
|
Theta2.grad.zero_() |
|
|
|
|
|
iter_count += 1 |
|
prev_cost = cost |
|
|
|
|
|
print("Final values: Theta0 = {}, Theta1 = {}, Theta2 = {}".format(Theta0.item(), Theta1.item(), Theta2.item())) |
|
print("Final Cost: Cost = {}".format(cost.item())) |
|
print("Final values: y_pred = {}, y_actual = {}".format(y_pred, y_actual)) |
|
|