Skip to content

Commit df4a6b5

Browse files
author
lck6055
committed
Added new Directory Ml and implemented basic algos
1 parent 9fd1b95 commit df4a6b5

2 files changed

Lines changed: 113 additions & 0 deletions

File tree

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
# Linear Regression using Gradient Descent (Full-Batch and SGD)
5+
6+
# Dataset
7+
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
8+
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
9+
10+
# Gradient Descent Function
11+
def gradient_descent(x, y, lr=0.01, epochs=10000, tolerance=1e-6, stochastic=False):
12+
b0, b1 = 0, 0
13+
n = len(x)
14+
15+
for epoch in range(epochs):
16+
if stochastic:
17+
# Stochastic (single sample)
18+
i = np.random.randint(0, n)
19+
xi, yi = x[i], y[i]
20+
y_pred = b0 + b1 * xi
21+
b0_grad = -(yi - y_pred)
22+
b1_grad = -(yi - y_pred) * xi
23+
else:
24+
# Batch Gradient Descent
25+
y_pred = b0 + b1 * x
26+
b0_grad = -np.sum(y - y_pred) / n
27+
b1_grad = -np.sum((y - y_pred) * x) / n
28+
29+
# Update parameters
30+
b0_new = b0 - lr * b0_grad
31+
b1_new = b1 - lr * b1_grad
32+
33+
# Check convergence
34+
if abs(b0_new - b0) < tolerance and abs(b1_new - b1) < tolerance:
35+
break
36+
37+
b0, b1 = b0_new, b1_new
38+
39+
return b0, b1
40+
41+
42+
# Full-Batch Gradient Descent
43+
b0_gd, b1_gd = gradient_descent(x, y, lr=0.01, epochs=10000, stochastic=False)
44+
y_pred_gd = b0_gd + b1_gd * x
45+
46+
# Stochastic Gradient Descent
47+
b0_sgd, b1_sgd = gradient_descent(x, y, lr=0.01, epochs=10000, stochastic=True)
48+
y_pred_sgd = b0_sgd + b1_sgd * x
49+
50+
# Compute metrics
51+
SST = np.sum((y - np.mean(y))**2)
52+
SSE_gd = np.sum((y - y_pred_gd)**2)
53+
SSE_sgd = np.sum((y - y_pred_sgd)**2)
54+
R2_gd = 1 - (SSE_gd / SST)
55+
R2_sgd = 1 - (SSE_sgd / SST)
56+
57+
# Print results
58+
print("=== Gradient Descent (Full-Batch) ===")
59+
print(f"Intercept (b0): {b0_gd:.4f}, Slope (b1): {b1_gd:.4f}")
60+
print(f"SSE: {SSE_gd:.4f}, R²: {R2_gd:.4f}")
61+
62+
print("\n=== Gradient Descent (Stochastic) ===")
63+
print(f"Intercept (b0): {b0_sgd:.4f}, Slope (b1): {b1_sgd:.4f}")
64+
print(f"SSE: {SSE_sgd:.4f}, R²: {R2_sgd:.4f}")
65+
66+
# Plot comparison
67+
plt.scatter(x, y, color="blue", label="Data")
68+
plt.plot(x, y_pred_gd, "g--", label="Batch Gradient Descent")
69+
plt.plot(x, y_pred_sgd, "m:", label="Stochastic GD")
70+
plt.xlabel("x")
71+
plt.ylabel("y")
72+
plt.legend()
73+
plt.title("Linear Regression using Gradient Descent (Batch & Stochastic)")
74+
plt.show()
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
# --- Linear Regression using Analytical (Closed-form) Solution ---
5+
6+
# Dataset
7+
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
8+
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
9+
10+
# Mean values
11+
x_mean, y_mean = np.mean(x), np.mean(y)
12+
13+
# Compute coefficients (Closed-form)
14+
b1 = np.sum((x - x_mean) * (y - y_mean)) / np.sum((x - x_mean)**2)
15+
b0 = y_mean - b1 * x_mean
16+
17+
# Predictions
18+
y_pred = b0 + b1 * x
19+
20+
# Compute SSE and R²
21+
SSE = np.sum((y - y_pred)**2)
22+
SST = np.sum((y - y_mean)**2)
23+
R2 = 1 - (SSE / SST)
24+
25+
# Print results
26+
print("=== Linear Regression (Analytical Solution) ===")
27+
print(f"Intercept (b0): {b0:.4f}")
28+
print(f"Slope (b1): {b1:.4f}")
29+
print(f"SSE: {SSE:.4f}")
30+
print(f"R²: {R2:.4f}")
31+
32+
# Plot results
33+
plt.scatter(x, y, color="blue", label="Data")
34+
plt.plot(x, y_pred, "r-", label="Analytical Solution")
35+
plt.xlabel("x")
36+
plt.ylabel("y")
37+
plt.legend()
38+
plt.title("Linear Regression - Analytical Solution")
39+
plt.show()

0 commit comments

Comments
 (0)