
Write a Python function that performs linear regression using the normal equation. The function should take a matrix X (features) and a vector y (target) as input, and return the coefficients of the linear regression model. Round your answer to four decimal places, -0.0 is a valid result for rounding a very small number.
Example:
- Input:
X = [[1, 1], [1, 2], [1, 3]], y = [1, 2, 3] - Output:
[0.0, 1.0]
《简单线性回归》之前才写过。
这次使用Normal equation来求解。

这个公式如上所示,很容易推出来。线性代数不熟悉的话,可能不清楚为什么要用XT,这是因为X不一定是方阵,而XTX就肯定是个方阵。需要有个方阵来求逆矩阵。
代码就比较简单,按照公式来运算即可:
import numpy as np
def linear_regression_normal_equation(X: list[list[float]], y: list[float]) -> list[float]:
# Your code here, make sure to round
X = np.array(X)
Xt = X.T
A = Xt @ X
theta = np.linalg.pinv(A) @ Xt @ y
return np.round(theta, 4).tolist()
