app.py
Browse files
app.py
CHANGED
@@ -1,20 +1,51 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
3 |
|
4 |
-
#
|
5 |
-
|
6 |
-
|
7 |
|
8 |
-
#
|
9 |
-
|
|
|
|
|
10 |
|
11 |
-
#
|
12 |
-
|
13 |
|
14 |
-
#
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Input data
|
2 |
+
x1 = [50, 60, 70, 80, 90]
|
3 |
+
x2 = [20, 21, 22, 23, 24]
|
4 |
+
y_actual = [30, 35, 40, 45, 50]
|
5 |
|
6 |
+
# Learning rate and maximum number of iterations
|
7 |
+
alpha = 0.01
|
8 |
+
max_iters = 1000
|
9 |
|
10 |
+
# Initial values for Theta0 and Theta1
|
11 |
+
Theta0 = 0
|
12 |
+
Theta1 = 0
|
13 |
+
Theta2 = 0
|
14 |
|
15 |
+
# Start the iteration counter
|
16 |
+
iter_count = 0
|
17 |
|
18 |
+
# Loop until convergence or maximum number of iterations
|
19 |
+
while iter_count < max_iters:
|
20 |
+
# Compute the predicted output
|
21 |
+
y_pred = [Theta0 + Theta1 * x1[i] + Theta2 * x2[i] for i in range(len(x1))]
|
22 |
|
23 |
+
|
24 |
+
# Compute the errors
|
25 |
+
errors = [y_pred[i] - y_actual[i] for i in range(len(x1))]
|
26 |
+
|
27 |
+
# Update Theta0 and Theta1
|
28 |
+
Theta0 -= alpha * sum(errors) / len(x1)
|
29 |
+
Theta1 -= alpha * sum([errors[i] * x1[i] for i in range(len(x1))]) / len(x1)
|
30 |
+
Theta2 -= alpha * sum([errors[i] * x2[i] for i in range(len(x2))]) / len(x2)
|
31 |
+
|
32 |
+
# Compute the cost function
|
33 |
+
cost = sum([(y_pred[i] - y_actual[i]) ** 2 for i in range(len(x1))]) / (2 * len(x1))
|
34 |
+
|
35 |
+
# Print the cost function every 100 iterations
|
36 |
+
if iter_count % 100 == 0:
|
37 |
+
print("Iteration {}: Cost = {}, Theta0 = {}, Theta1 = {}".format(iter_count, cost, Theta0, Theta1, Theta2))
|
38 |
+
|
39 |
+
# Check for convergence (if the cost is decreasing by less than 0.0001)
|
40 |
+
if iter_count > 0 and abs(cost - prev_cost) < 0.0001:
|
41 |
+
print("Converged after {} iterations".format(iter_count))
|
42 |
+
break
|
43 |
+
|
44 |
+
# Update the iteration counter and previous cost
|
45 |
+
iter_count += 1
|
46 |
+
prev_cost = cost
|
47 |
+
|
48 |
+
# Print the final values of Theta0 and Theta1
|
49 |
+
print("Final values: Theta0 = {}, Theta1 = {}".format(Theta0, Theta1, Theta2))
|
50 |
+
print("Final Cost: Cost= {}".format(cost))
|
51 |
+
print("Final values: y_pred = {}, y_actual = {}".format(y_pred, y_actual))
|