|
|
|
x1 = [50, 60, 70, 80, 90] |
|
x2 = [20, 21, 22, 23, 24] |
|
y_actual = [30, 35, 40, 45, 50] |
|
|
|
|
|
alpha = 0.01 |
|
max_iters = 1000 |
|
|
|
|
|
Theta0 = 0 |
|
Theta1 = 0 |
|
Theta2 = 0 |
|
|
|
|
|
iter_count = 0 |
|
|
|
|
|
while iter_count < max_iters: |
|
|
|
y_pred = [Theta0 + Theta1 * x1[i] + Theta2 * x2[i] for i in range(len(x1))] |
|
|
|
|
|
|
|
errors = [y_pred[i] - y_actual[i] for i in range(len(x1))] |
|
|
|
|
|
Theta0 -= alpha * sum(errors) / len(x1) |
|
Theta1 -= alpha * sum([errors[i] * x1[i] for i in range(len(x1))]) / len(x1) |
|
Theta2 -= alpha * sum([errors[i] * x2[i] for i in range(len(x2))]) / len(x2) |
|
|
|
|
|
cost = sum([(y_pred[i] - y_actual[i]) ** 2 for i in range(len(x1))]) / (2 * len(x1)) |
|
|
|
|
|
if iter_count % 100 == 0: |
|
print("Iteration {}: Cost = {}, Theta0 = {}, Theta1 = {}".format(iter_count, cost, Theta0, Theta1, Theta2)) |
|
|
|
|
|
if iter_count > 0 and abs(cost - prev_cost) < 0.0001: |
|
print("Converged after {} iterations".format(iter_count)) |
|
break |
|
|
|
|
|
iter_count += 1 |
|
prev_cost = cost |
|
|
|
|
|
print("Final values: Theta0 = {}, Theta1 = {}".format(Theta0, Theta1, Theta2)) |
|
print("Final Cost: Cost= {}".format(cost)) |
|
print("Final values: y_pred = {}, y_actual = {}".format(y_pred, y_actual)) |
|
|