1、线性回归

基本思想:线性回归是一种用于建立自变量和因变量之间线性关系的经典统计方法,其基本思想是找到一条最佳的直线,使得这条直线能够最好地拟合样本数据,并用这条直线来对新的自变量进行预测。

2、 代码实现

2.1.metrics.py:定义一些衡量模型的性能的指标
包括分类和回归的指标

import numpy as np
from math import sqrt# 分类准确度
def accuracy_score(y_true, y_predict):"""计算y_true(y_test)和y_predict之间的准确率"""assert y_true.shape[0] == y_predict.shape[0], \"the size of y_true must be equal to the size of y_predict"return np.sum(y_true == y_predict) / len(y_true)# 下面三个是对线性回归模型大的评测指标
def mean_squared_error(y_true, y_predict):"""计算y_true和y_predict之间的mse"""assert len(y_true) == len(y_predict), \"the size of y_true must be equal to the size of y_predict"return np.sum((y_true - y_predict) ** 2) / len(y_true)def root_mean_squared_error(y_true, y_predict):"""计算y_true和y_predict之间的RMSE"""return sqrt(mean_squared_error(y_true, y_predict))def mean_absolute_error(y_true, y_predict):"""计算y_true和y_predict之间的RMSE"""assert len(y_true) == len(y_predict), \"the size of y_true must be equal to the size of y_predict"return np.sum(np.absolute(y_true - y_predict)) / len(y_true)def r2_score(y_true, y_predict):"""计算y_true和y_predict之间的R Square"""return 1 - mean_squared_error(y_true, y_predict) / np.var(y_true)# 评价分类的指标
def TN(y_true, y_predict):assert len(y_true) == len(y_predict)return np.sum((y_true == 0) & (y_predict == 0))def FP(y_true, y_predict):assert len(y_true) == len(y_predict)return np.sum((y_true == 0) & (y_predict == 1))def FN(y_true, y_predict):assert len(y_true) == len(y_predict)return np.sum((y_true == 1) & (y_predict == 0))def TP(y_true, y_predict):assert len(y_true) == len(y_predict)return np.sum((y_true == 1) & (y_predict == 1))def confusion_matrix(y_true, y_predict):return np.array([[TN(y_true, y_predict), FP(y_true, y_predict)],[FN(y_true, y_predict), TP(y_true, y_predict)]])def precision_score(y_true, y_predict):tp = TP(y_true, y_predict)fp = FP(y_true, y_predict)try:return tp / (tp + fp)except:return 0.0def recall_score(y_true, y_predict):tp = TP(y_true, y_predict)fn = FN(y_true, y_predict)try:return tp / (tp + fn)except:return 0.0def f1_score(y_true, y_predict):precision = precision_score(y_true, y_predict)recall = recall_score(y_true, y_predict)try:return 2 * precision * recall / (precision + recall)except:return 0.0def TPR(y_true, y_predict):tp = TP(y_true, y_predict)fn = FN(y_true, y_predict)try:return tp / (tp + fn)except:return 0.0def FPR(y_true, y_predict):fp = FP(y_true, y_predict)tn = TN(y_true, y_predict)try:return fp / (fp + tn)except:return 0.0

上面的代码是一些评估机器学习模型表现的函数,包括回归模型和分类模型的指标。下面是每个函数的具体功能描述:
accuracy_score(y_true, y_predict):计算分类模型的准确率。
mean_squared_error(y_true, y_predict):计算回归模型的均方误差。
root_mean_squared_error(y_true, y_predict):计算回归模型的均方根误差。
mean_absolute_error(y_true, y_predict):计算回归模型的平均绝对误差。
r2_score(y_true,y_predict):计算回归模型的R²分数。
TN(y_true, y_predict):计算二分类模型中真负类数。
FP(y_true,y_predict):计算二分类模型中假正类数。
FN(y_true, y_predict):计算二分类模型中假负类数。
TP(y_true, y_predict):计算二分类模型中真正类数。
confusion_matrix(y_true,y_predict):计算二分类模型中的混淆矩阵。
precision_score(y_true,y_predict):计算二分类模型中的精确率。
recall_score(y_true, y_predict):计算二分类模型中的召回率。
f1_score(y_true, y_predict):计算二分类模型中的F1分数。
TPR(y_true,y_predict):计算二分类模型中的真正类率。
FPR(y_true, y_predict):计算二分类模型中的假正类率。

2.2.LinearRegression.py:封装的线性回归模型
损失函数:均方误差(MSE)

优化方法:梯度下降 or 向量化运算求梯度

import numpy as np
from .metrics import r2_score# 多元线性回归模型
class LinearRegression:def __init__(self):"""初始化Linear Regression模型"""self.coef_ = None  # 系数self.interception_ = None  # 截距self._theta = None# 使用正规化解出参数def fit_normal(self, X_train, y_train):"""根据训练数据集X_train, y_train训练Linear Regression模型"""assert X_train.shape[0] == y_train.shape[0], \"the size of X_train must be equal to the size of y_train"# X_b = np.hstack([np.ones((X_train.shape[0], 1)), X_train])X_b = np.hstack([np.ones((X_train.shape[0], 1)), X_train])self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)self.interception_ = self._theta[0]self.coef_ = self._theta[1:]return self# 使用批量梯度下降法def fit_gd(self, X_train, y_train, eta=0.01, n_iters=1e4):"""根据训练数据集X_train, y_train,使用梯度下降法训练Linear Regression模型"""assert X_train.shape[0] == y_train.shape[0], \"the size of X_train must be equal to the size of y_train"def J(theta, X_b, y):"""求出对应theta的损失函数"""try:return np.sum((y - X_b.dot(theta)) ** 2) / len(y)except:return float('inf')def dJ(theta, X_b, y):"""求出损失函数的对应theta梯度"""# 使用循坏计算# res = np.empty(len(theta))# res[0] = np.sum(X_b.dot(theta)-y)# for i in range(1, len(theta)):#     res[i] = (X_b.dot(theta) - y).dot(X_b[:, i])# return res * 2 / len(X_b)# 使用下面向量化运算求梯度return X_b.T.dot(X_b.dot(theta) - y) * 2 / len(y)def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):"""使用梯度下降算法训练模型"""theta = initial_thetacur_iter = 0while cur_iter < n_iters:gradient = dJ(theta, X_b, y)last_theta = thetatheta = theta - eta * gradientif abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon:breakcur_iter += 1return thetaX_b = np.hstack([np.ones((len(X_train), 1)),  X_train])initial_theta = np.zeros(X_b.shape[1])self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)self.interception_ = self._theta[0]self.coef_ = self._theta[1:]return self# 使用随机梯度下降法  在随机梯度下降法中,通常n_iters:表示将所有样本数据看几遍(考虑到所有训练样本信息)#  n_iters:默认将所有样本数据看5遍def fit_sgd(self, X_train, y_train, n_iters=5, t0=5, t1=50):"""根据训练数据集X_train, y_train,使用梯度下降法训练Linear Regression模型"""assert X_train.shape[0] == y_train.shape[0], \"the size of X_train must be equal to the size of y_train"assert n_iters >= 1, \"All sample data should be considered at least once"def dJ_sgd(theta, X_b_i, y_i):     # 随机梯度下降传进来的是一个样本的数据return X_b_i.T.dot(X_b_i.dot(theta) - y_i) * 2.   # 不需要除以len(y)def sgd(X_b, y, initial_theta, n_iters, t0=5, t1=50):def learning_rate(t):return t0 / (t + t1)theta = initial_thetam = len(X_b)     #样本的数量"""1、下面的实现方法有问题:随机梯度下降法应该把所有的样本数据至少看一遍,把所有的样本信息都考虑到(即都能用上,这样比较科学)"""# for cur_iter in range(n_iters*m):#     rand_i = np.random.randint(m)  # 1.1 随机选取一个样本数据, 因为是随机取一个样本,所以不能保证所有样本的信息都考虑到#     gradient = dJ_sgd(theta, X_b[rand_i], y[rand_i])#     theta = theta - learning_rate(cur_iter) * gradient## 2、为解决1.1的问题,下面对代码进行改进for cur_iter in range(n_iters):indexes = np.random.permutation(m)   #生成0到m-1的乱序数组X_b_new = X_b[indexes]y_new = y[indexes]for i in range(m):gradient = dJ_sgd(theta, X_b_new[i], y_new[i])theta = theta - learning_rate(cur_iter * m + i) * gradientreturn thetaX_b = np.hstack([np.ones((len(X_train), 1)),  X_train])initial_theta = np.random.randn(X_b.shape[1])self._theta = sgd(X_b, y_train, initial_theta, n_iters, t0, t1)self.interception_ = self._theta[0]self.coef_ = self._theta[1:]return selfdef predict(self, X_predict):"""给定待预测数据集X_predict,返回表示X_predict"""assert self.coef_ is not None and self.interception_ is not None, \"must fit before predict!"assert X_predict.shape[1] == len(self.coef_), \"the feature number of X_predict must be equal to X_train"X_b = np.hstack([np.ones((X_predict.shape[0], 1)), X_predict])return X_b.dot(self._theta)def score(self, X_test, y_test):"""根据测试数据集X_test和y_test确定当前模型的准确度"""y_predict = self.predict(X_test)return r2_score(y_test, y_predict)def __repr__(self):return "LinearRegression()"

代码实现了一个多元线性回归模型,其中包括三种不同的参数训练方法:正规方程法、批量梯度下降法和随机梯度下降法。
模型的训练需要传入训练数据集 X_train 和 y_train。其中,X_train 为训练集的自变量数据,y_train 为训练集的因变量数据。
在正规方程法中,模型直接使用正规方程求解出最优参数;
在批量梯度下降法中,模型使用梯度下降法求解最优参数,其中需要传入梯度下降法的参数包括:学习率 eta、迭代次数 n_iters;
在随机梯度下降法中,模型同样使用梯度下降法求解最优参数,但是每次迭代只随机选择一个样本进行梯度下降,因此其训练速度相比批量梯度下降法更快,需要传入的参数包括迭代次数 n_iters、学习率更新的相关参数 t0 和 t1。

Time:2023.3.13
如果上面代码对您有帮助,欢迎点个赞!!!

机器学习--线性回归模型(LinearRegression)相关推荐

  1. 机器学习--线性回归(LinearRegression)

    机器学习–线性回归 基本概念 LinearRegression 拟合一个带有系数 w=(w1,...,wp)w = (w_1, ..., w_p)w=(w1​,...,wp​) 的线性模型,使得数据集 ...

  2. python线性拟合模型_Python机器学习-线性回归模型篇

    一.What机器学习是什么 机器学习简单来说,是从数据中归纳出有用的规则,它是一种新的编程方式,它不需要人类来总结经验.输入逻辑,人类只需要把大量数据输入计算机,然后计算机就可以自动总结经验归纳逻辑, ...

  3. 机器学习算法——线性回归的详细介绍 及 利用sklearn包实现线性回归模型

    目录 1.线性回归简介 1.1 线性回归应用场景 1.2 什么是线性回归 1.2.1 定义与公式 1.2.2 线性回归的特征与目标的关系分析 2.线性回归api初步使用 2.1 线性回归API 2.2 ...

  4. 机器学习入门实践——线性回归模型(波士顿房价预测)

    机器学习入门实践--线性回归模型(波士顿房价预测) 一.背景介绍 给定一个大小为 n n n的数据集 { y i , x i 1 , . . . , x i d } i = 1 n {\{y_{i}, ...

  5. cmd装b专用代码_Python 用5行代码学机器学习—线性回归

    我准备使用scikit-learn给大家介绍一些模型的基础知识,今天就来讲讲线性回归模型. 1. 准备 开始之前,你要确保Python和pip已经成功安装在电脑上噢,如果没有,请访问这篇文章:超详细P ...

  6. python 线性回归模型_如何在Python中建立和训练线性和逻辑回归ML模型

    python 线性回归模型 Linear regression and logistic regression are two of the most popular machine learning ...

  7. 机器学习——线性回归、房价预测案例【正规方案与梯度下降】

    # coding:utf-8 # 1.获取数据集 #2.数据基本处理 #2.1.数据划分 #3.特征工程--标准化 #4.机器学习(线性回归) #5.模型评估 from sklearn.dataset ...

  8. 机器学习线性回归算法实验报告_机器学习之简单线性回归

    为了利用机器学习进行简单的线性回归,先理解机器学习和线性回归的概念,然后通过案例进行机器学习.本文主要目录如下: 一.机器学习的概念 二.线性回归的概念 三.机器学习线性回归模型 (一)导入数据集 ( ...

  9. 线性回归模型详解(Linear Regression)

    目录 线性与非线性 线性回归 多重共线性 常用的回归模型评估指标 算法优缺点 算法实现 回归分析的主要算法包括: 线性回归(Linear Regression) 逻辑回归(Logistic regre ...

最新文章

  1. Map集合练习之对字符串中字母出现的次数求和
  2. 得到相对Plugin的路径
  3. DataParallel 笔记
  4. Java接口有时有结果 有时没有_《Java程序员面试笔试宝典》之为什么Java中有些接口没有任何方法...
  5. ICCV 2019丨基于跨视角信息融合的三维人体姿态估计
  6. 从环境搭建到回归神经网络案例,带你掌握Keras
  7. 关于K-SVD算法中逐列更新的目标函数的理解,再看不懂就打死我吧
  8. Operating System-进程间互斥的方案-保证同一时间只有一个进程进入临界区(3)- TSL指令...
  9. SpringBoot整合Dubbo案例
  10. Intellij IDEA问题解决合集
  11. 常用公共数据集----数据获取
  12. 从零开始学习OpenWrt完美教程
  13. 【教程下载】QGIS的安装及中文配置教程.pdf
  14. nmap扫描服务器端口不稳定,nmap端口扫描问题
  15. 支付宝小程序获取用户手机号php,小程序登录、获取用户信息、手机号
  16. PTGUI 全景图批量拼接
  17. 261期计算机开机号,福彩3D2017第261期彩吧3D开机号147
  18. 网络编程培训之一 编程实现IP/TCP/UDP报文
  19. css3 搜索栏 圆角,CSS3 圆角
  20. bat批处理文件编写

热门文章

  1. word拼写检查自定义词典下载_如何在Word中限制拼写检查到主词典 | MOS86
  2. Linux学习笔记之编码转换
  3. 工业互联网蓬勃发展,出奇才能制胜
  4. KingbaseES PL/SQL 过程语言参考手册(3. PL/SQL语言基础)
  5. 互联网从业者高频单词 300个
  6. jQuery自适应栅格式左右滑动轮播卡片式table
  7. 网站漏洞修补 Kindeditor上传漏洞
  8. attck是什么,特点是啥
  9. Java游戏开发编写源码
  10. PHP(1) Error: php@7.4 has been disabled because it is a versioned formula