提交 71a97d8b 编写于 作者: wit-df's avatar wit-df

上传新文件

上级 30db8d00
import numpy as np
# 线性回归(正规方程法)
class LinearRegression_Equation:
# 根据公式计算w,是n*1的2维矩阵
def fit(self, X, y):
self.w = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
# 根据公式(4.1)计算预测结果,是m*1的2维矩阵
def predict(self, X):
return X.dot(self.w)
# 线性回归(梯度下降法)
class LinearRegression_GD:
def __init__(self,
N = 1000, # 训练轮数
lr = 0.01 # 学习率
) -> None:
self.N = N
self.lr = lr
def fit(self, X, y):
m, n = X.shape
w = np.zeros((n, 1))
y = y.reshape(-1, 1)
for _ in range(self.N):
gradient = 1 / m * X.T.dot(X.dot(w) - y)
w -= self.lr * gradient
self.w = w
def predict(self, X):
return X.dot(self.w)
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册