#92 · Machine Learning · Medium
⊣ Solve on deep-ml.comImplement linear regression for power grid optimization. Given features (e.g., temperature, demand) and target values (power output), fit a linear regression model using the normal equation and return the predicted values and model coefficients.
import numpy as np
def linear_regression(X: np.ndarray, y: np.ndarray) -> tuple:
# Add bias column
m = X.shape[0]
X_b = np.column_stack([np.ones(m), X])
# Normal equation: theta = (X^T X)^(-1) X^T y
theta = np.linalg.inv(X_b.T @ X_b) @ X_b.T @ y
predictions = X_b @ theta
return theta, predictionstheta = (X^T X)^{-1} X^T y. This gives the closed-form least-squares solution.The normal equation avoids iterative optimization (no learning rate or epochs needed) but requires the matrix X^T X to be invertible.