Post

Test Post 2

Understanding how gradient descent optimizes a linear regression model is essential as a foundation before moving on to more complex machine learning algorithms. The core idea is to iteratively adjust model parameters so the prediction error shrinks toward a minimum.

Linear Regression Graph Illustration

Using Mean Squared Error with an L2 regularization term over $n$ training samples, the objective cost function is defined as:

\[J(w, b) = \frac{1}{2n} \sum_{i=1}^{n} \left( (w x_i + b) - y_i \right)^2 + \frac{\lambda}{2n} w^2\]

The Python implementation below computes predictions, evaluates the cost, and updates parameters using gradient descent.

```python import numpy as np

def compute_cost( x: np.ndarray, y: np.ndarray, w: float, b: float, lam: float = 0.01 ) -> float: “"”Compute regularized Mean Squared Error cost J(w, b).””” n = len(x) predictions = w * x + b mse_term = np.sum((predictions - y) ** 2) / (2.0 * n) reg_term = (lam / (2.0 * n)) * (w**2) return float(mse_term + reg_term)

def compute_gradients( x: np.ndarray, y: np.ndarray, w: float, b: float, lam: float = 0.01 ) -> tuple[float, float]: “"”Compute partial derivatives dJ/dw and dJ/db.””” n = len(x) error = (w * x + b) - y dw = (np.sum(error * x) / n) + ((lam / n) * w) db = np.sum(error) / n return float(dw), float(db)

def gradient_descent( x: np.ndarray, y: np.ndarray, w_init: float = 0.0, b_init: float = 0.0, alpha: float = 0.01, lam: float = 0.01, epochs: int = 1000, ) -> tuple[float, float, list[float]]: “"”Iteratively update w and b to minimize J(w, b).””” w = w_init b = b_init cost_history: list[float] = []

for step in range(epochs): dw, db = compute_gradients(x, y, w, b, lam) w = w - alpha * dw b = b - alpha * db

1
2
3
if step % 100 == 0 or step == epochs - 1:
  cost = compute_cost(x, y, w, b, lam)
  cost_history.append(cost)

return w, b, cost_history

if name == “main”: x_train = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) y_train = np.array([2.2, 4.1, 5.8, 8.1, 9.9, 12.1])

w_final, b_final, history = gradient_descent( x_train, y_train, alpha=0.02, lam=0.05, epochs=1500 )

print(f”Learned parameters -> w: {w_final:.4f}, b: {b_final:.4f}”) print(f”Final cost: {history[-1]:.6f}”) for idx, val in enumerate(history): print(f”Checkpoint {idx * 100}: cost = {val:.6f}”)

This post is licensed under CC BY 4.0 by the author.

Trending Tags