Problems
Loading...
1 / 1

Linear Regression Closed Form

Linear AlgebraClassic ML
Medium

Linear regression finds the weight vector that minimizes the sum of squared errors between predictions and targets. The closed-form solution (the normal equation) computes the optimal weights directly using matrix algebra, without iterative optimization.

Given a feature matrix XX and a target vector yy, compute the weight vector ww using the normal equation.

Formula

w=(XTX)1XTyw = (X^T X)^{-1} X^T y

Where XX is the n×dn \times d feature matrix (nn samples, dd features), yy is the nn-dimensional target vector, and ww is the dd-dimensional weight vector.

Loading visualization...

Examples

Input: X=[[1],[2],[3]]X = [[1], [2], [3]], y=[2,4,6]y = [2, 4, 6]

Output: [2.0][2.0]

The line y=2xy = 2x perfectly fits the data.

Input: X=[[1,1],[1,2],[1,3]]X = [[1, 1], [1, 2], [1, 3]], y=[3,5,7]y = [3, 5, 7]

Output: [1.0,2.0][1.0, 2.0]

The first column acts as a bias. The model y=1+2xy = 1 + 2x fits perfectly.

Hint 1

Look into np.linalg.inv\texttt{np.linalg.inv} for computing (XTX)1(X^T X)^{-1}.

Hint 2

NumPy's @\texttt{@} operator chains matrix multiplications, so the entire formula can fit in one expression.

Requirements

  • Use numpy to convert XX and yy to arrays
  • Compute the transpose XTX^T
  • Compute the products XTXX^T X and XTyX^T y
  • Compute the inverse (XTX)1(X^T X)^{-1}
  • Multiply the inverse by XTyX^T y to get ww
  • Return a list of floats or a numpy array

Constraints

  • XX has at least as many rows as columns (nd)(n \geq d)
  • XTXX^T X is always invertible
  • Return length must equal dd, the number of columns in XX
  • numpy is available as np\texttt{np}
  • Time limit: 300 ms
Try Similar Problems