初级算法梳理(二)——线性回归

1、线性回归
线性:输入和输出变量之间的关系为一次方函数,即在空间上是一条直线。
回归:在模型(函数、关系式、映射关系等)中输入数据,输出的结果是连续的值,这个过程叫回归。ps:回归是典型的监督学习。
线性回归:在N维空间中使用直线方程拟合数据的过程。

2、损失函数
损失函数(Loss Function):度量单样本预测的错误程度,损失函数值越小,模型就越好。
代价函数(Cost Function):度量全部样本集的平均误差。
目标函数(Object Function):代价函数和正则化函数,最终要优化的函数。

我们追求损失函数值越小越好。
是不是损失函数最小就好呢?答案是否定的?
因为随着函数复杂度提高,模型会出现过拟合。
如何解决呢?通过定义复杂度函数防止结构化风险

3、线性回归的优化方法
常用的有梯度下降法、最小二乘法矩阵求解、牛顿法、拟牛顿法等

4、线性回归的实现方法比较
运用sklearn中线性模型的代码比较方便
最小二乘法和梯度下降法需要依据原理一步一步写代码。

5、具体实现(三种方法比较)
第一步:生成数据

import numpy as ny  
#生成随机数
np.random.seed(1234)
x = np.random.rand(500,3)
#构建映射关系,模拟真实的数据待预测值,映射关系为y = 4.2 + 5.7*x1 + 10.8*x2,可自行设置值进行尝试
y = x.dot(np.array([4.25,7,10.8]))

第一种方法:调用sklearn的线性回归模型训练数据

import numpy as ny
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline

#调用模型
lr = LinearRegression(fit_intercept=True)
#训练模型
lr.fit(x,y)
print("估计的参数值为:%s" %(lr.coef_))
# 计算R平方
print('R2:%s' %(lr.score(x,y)))
# 任意设定变量,预测目标值
x_test = np.array([2,4,5]).reshape(1,-1)
y_hat = lr.predict(x_test)
print("预测值为: %s" %(y_hat))

第二种方法

class LR_LS():
    def __init__(self):
        self.w = None      
    def fit(self, X, y):
        # 最小二乘法矩阵求解
        temp0 = np.dot(X.T,X)
        temp = np.dot(np.linalg.inv(tempo),X.T)
        self.w = np.dot(temp,y)
        return self.w
    def predict(self, X):
        # 用已经拟合的参数值预测新自变量
        y_pred = np.dot(X,self.w)
        return y_pred

if __name__ == "__main__":
    lr_ls = LR_LS()
    lr_ls.fit(x,y)
    print("估计的参数值:%s" %(lr_ls.w))
    x_test = np.array([2,4,5]).reshape(1,-1)
    print("预测值为: %s" %(lr_ls.predict(x_test)))

第三种方法

class LR_GD():
    def __init__(self):
        self.w = None     
    def fit(self,X,y,alpha=0.02,loss = 1e-10): # 设定步长为0.002,判断是否收敛的条件为1e-10
        y = y.reshape(-1,1) #重塑y值的维度以便矩阵运算
        [m,d] = np.shape(X) #自变量的维度
        self.w = np.zeros((d)).reshape(d,1)#将参数的初始值定为0
        tol = 1e5
        while tol > loss:
            temp = X.dot(self.w)-y
            self.w = self.w-1/m*alpha*(temp.dot(X))
            tol = np.abs(np.sum(temp))
    def predict(self, X):
        # 用已经拟合的参数值预测新自变量
        y_pred = X.dot(self.w)
        return y_pred  
        
if __name__ == "__main__":
    lr_gd = LR_GD()
    lr_gd.fit(x,y)
    print("估计的参数值为:%s" %(lr_gd.w))
    x_test = np.array([2,4,5]).reshape(1,-1)
    print("预测值为:%s" %(lr_gd.predict(x_test)))

发布了8 篇原创文章 · 获赞 1 · 访问量 187

猜你喜欢

转载自blog.csdn.net/Moby97/article/details/103941124