题解 | 使用正规方程的线性回归
使用正规方程的线性回归
https://www.nowcoder.com/practice/c497c2c49ea843898731bb14accc04ac
import numpy as np def linear_regression_normal_equation( X: list[list[float]], y: list[float] ) -> list[float]: # 实现代码 X_transpose = X.T # 计算正规方程的解 theta = np.linalg.inv(X_transpose.dot(X)).dot(X_transpose).dot(y) theta = np.round(theta, 4).flatten().tolist() return theta if __name__ == "__main__": import ast x = np.array(ast.literal_eval(input())) y = np.array(ast.literal_eval(input())).reshape(-1, 1) # Perform linear regression coefficients = linear_regression_normal_equation(x, y) # Print the coefficients print(coefficients)