这里主要记录多项式线性回归,会附带一部分简单线性回归的讲解
线性回归其实是典型的参数训练的机器学习方法,而且专门解决回归问题
首先先讲下简单线性回归
简单线性回归
函数表达式
y=ax+b
其中
代码实现
import numpy as np
import matplotlib.pyplot as plt
class SimpleLinearRegression:
def __init__(self):
self.a_ = None
self.b_ = None
#模型训练
def fit(self, x, y):
assert x.ndim == 1, "illegle x"
assert len(x) == len(y), "this size of x_train must be equal to the size of y_train"
num = 0
d = 0
# 用for循环耗时长,需要消耗大量的计算资源
# for x_i, y_i in zip(x, y):
# num += (x_i - np.mean(x))*(y_i - np.mean(y))
# d += (x_i - np.mean(x))**2
# 用向量点乘的方式可以让运算时长变短
num = (x-np.mean(x)).dot(y-np.mean(y))
d = (x-np.mean(x)).dot(x-np.mean(x))
self.a_ = num/d