IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 数据结构与算法 -> 线性回归算法 -> 正文阅读

[数据结构与算法]线性回归算法

简单线性回归

  • 简单线性回归包含一个自变量(x)和一个因变量(y),如果包含两个以上的自变量,则称作多元回归分析(multiple regression),被用来描述因变量(y)和自变量(X)以及偏差(error)之间关系的方程叫做回归模型
    • 公式:
      ∑ m = 0 m ( y ( i ) ? a ? x ( i ) ? b ) 2 ,一元线性回归算法公式 \sum_{m=0}^{m} ({y^{(i)} -a*x^{(i)}-b)^2} \text {,一元线性回归算法公式} m=0m?(y(i)?a?x(i)?b)2,一元线性回归算法公式
    • 原理:找到a和b使得上述公式的值尽可能的小,经过最小二乘法求解可以计算出a值是:
      a = ∑ m = 0 m ( x ( i ) ? x  ̄ ) ? ( y ( i ) ? y ˉ ) ∑ m = 0 m ( x ( i ) ? x ˉ ) 2 ,a的值 a=\frac{ \sum_{m=0}^{m}(x^{(i)}-\overline{x})*(y^{(i)}-\bar{y })}{ \sum_{m=0}^{m}(x^{(i)}-\bar{x })^2} \text {,a的值} a=m=0m?(x(i)?xˉ)2m=0m?(x(i)?x)?(y(i)?yˉ?)?a的值
      b = y ˉ ? a ? x ˉ ,b的值 b=\bar{y }-a*\bar{x }\text {,b的值} b=yˉ??a?xˉb的值
    • 使用代码实现如下:这种方式实现的代码时间复杂度很大O(n^3)不建议使用
class SimpleLinearRegression1:
    def __init__(self):
        self.a_ = None
        self.b_ = None

    def fit(self, x_train, y_train):
        """根据训练数据集x_train,y_train训练Simple Linear Regression模型"""
        if x_train.ndim != 1:
            raise Exception("简单回归的维度只能是一维")
        if len(x_train) != len(y_train):
            raise Exception("x_train的行数需要和y_train的行数相同")
        """计算训练集平均值"""
        x_mean = np.mean(x_train)
        """计算训练集平均值"""
        y_mean = np.mean(y_train)

        num = 0.0  # 分子
        d = 0.0  # 分母
        """循环得出x,y的值"""
        for x, y in zip(x_train, y_train):
            """利用最小二乘法计算出a、b的值"""
            num += (x - x_mean) * (y - y_mean)
            d += (x - x_mean) ** 2
        self.a_ = num / d
        self.b_ = y_mean - self.a_ * x_mean
        return self

    def predict(self, x_predict):
        """x_predict是待预测的数据集,输入这个x_predict会得到一个预测值"""
        if x_predict.ndim != 1:
            raise Exception("简单回归的维度只能是一维")
        if self.a_ is None and self.b_ is None:
            raise Exception("预测之前需要先拟合")
        res = []
        for x in x_predict:
            res.append(self._predict(x))
            """封装为np.array格式数据"""
        return np.array(res)

    def _predict(self, x_single):
        """转化为函数y=a*x+b"""
        return self.a_ * x_single + self.b_
  • 第二方式实现
    a = ( x ( i ) ? x  ̄ ) ? ( y ( i ) ? y ˉ ) ( x ( i ) ? x ˉ ) 2 ,a的值 a=\frac{(x^{(i)}-\overline{x})\cdot(y^{(i)}-\bar{y })}{ (x^{(i)}-\bar{x })^2} \text {,a的值} a=(x(i)?xˉ)2(x(i)?x)?(y(i)?yˉ?)?a的值
    b = y ˉ ? a ? x ˉ ,b的值 b=\bar{y }-a*\bar{x }\text {,b的值} b=yˉ??a?xˉb的值
    • 代码如下:
class SimpleLinearRegression2:
    def __init__(self):
        self.a_ = None
        self.b_ = None

    def fit(self, x_train, y_train):
        """根据训练数据集x_train,y_train训练Simple Linear Regression模型"""
        if x_train.ndim != 1:
            raise Exception("简单回归的维度只能是一维")
        if len(x_train) != len(y_train):
            raise Exception("x_train的行数需要和y_train的行数相同")
        x_mean = np.mean(x_train)
        y_mean = np.mean(y_train)

        num = 0.0  # 分子
        d = 0.0  # 分母
        num = (x_train - x_mean).dot(y_train - y_mean)
        d = (x_train - x_mean).dot(x_train - x_mean)
        self.a_ = num / d
        self.b_ = y_mean - self.a_ * x_mean
        return self

    def predict(self, x_predict):
        """x_predict是待预测的数据集,输入这个x_predict会得到一个预测值"""
        if x_predict.ndim != 1:
            raise Exception("简单回归的维度只能是一维")
        if self.a_ is None and self.b_ is None:
            raise Exception("预测之前需要先拟合")
        res = []
        for x in x_predict:
            res.append(self._predict(x))
        return np.array(res)

    def score(self, x_test, y_test):
        y_predict = self.predict(x_test)
        return r2_score(y_test, y_predict)

    def _predict(self, x_single):
        return self.a_ * x_single + self.b_
  • 评价一盒回归算法的好坏可以利用MSE(均方误差)、RMSE(均方根误差)、MAE(平均绝对误差)、R2(决定系数)实现代码如下
def mean_squared_error(y_true, y_predict):
    if len(y_true) != len(y_predict):
        raise Exception("y_ture的长度应该和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之间的MAE"""
    return np.sum(np.absolute(y_true - y_predict)) / len(y_true)


def r2_score(y_true, y_predict):
    return 1 - mean_squared_error(y_true, y_predict) / np.var(y_true)

多元线性回归:

  • 公式
    y = θ 0 + θ 1 x 1 + θ 2 x 2 + θ 3 x 3 + . . . . . . + θ n x n ,y的值 y=\theta_{0}+\theta_{1}x_{1}+\theta_{2}x_{2}+\theta_{3}x_{3}+......+\theta_{n}x_{n}\text {,y的值} y=θ0?+θ1?x1?+θ2?x2?+θ3?x3?+......+θn?xn?y的值
  • 分解这个函数可以得到:
    y ^ ( i ) = x 0 + x 1 + x 2 + x 3 + . . . . . . + x n \widehat{y}^{(i)}=x_{0}+x_{1}+x_{2}+x_{3}+......+x_{n} y ?(i)=x0?+x1?+x2?+x3?+......+xn?
    θ = ( θ 0 + θ 1 + θ 2 + θ 3 + . . . . . . + θ n ) T \theta_=(\theta_{0}+\theta_{1}+\theta_{2}+\theta_{3}+......+\theta_{n}) ^{T} θ=?(θ0?+θ1?+θ2?+θ3?+......+θn?)T根据向量化运算可以得到 θ = ( x b ? x b ) T ? x b T ? y \theta_=(x_{b}\cdot x_{b})^{T}\cdot x_{b}^{T}\cdot y θ=?(xb??xb?)T?xbT??y 函数的截距就是 θ 0 \theta_{0} θ0?系数是 θ 1 . . . . . . θ n \theta_{1}......\theta_{n} θ1?......θn?
  • y值,就是数学函数输出的值是
    y = x b ? θ y=x_{b}\cdot \theta_{} y=xb??θ? θ = ( x b ? x b ) T ? x b T ? y \theta_=(x_{b}\cdot x_{b})^{T}\cdot x_{b}^{T}\cdot y θ=?(xb??xb?)T?xbT??y
    np.hstack():在水平方向上平铺
    X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
  • 多元线性回归代码如下:
# -*- coding: utf-8 -*-
# @Time    : 2021/7/30 10:56
# @Email   : 2635681517@qq.co
import numpy as np

from metrics import r2_score


class LinearRegression:
    def __init__(self):
        self.coef_ = None
        self.intercept_ = None
        self.theta_ = None

    def fit_normal(self, X_train, y_train):
        """根据训练数据集X_train, y_train训练Linear Regression模型"""
        if X_train.shape[0] != y_train.shape[0]:
            raise Exception("X_train的行数需要和y_train的行数相同")
        X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
        self.theta_ = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)
        self.intercept_ = self.theta_[0]
        self.coef_ = self.theta_[1:]
        return self

    def predict(self, X_predict):
        """给定待预测数据集X_predict,返回表示X_predict的结果向量"""
        assert self.intercept_ is not None and self.coef_ 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((len(X_predict), 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()"

  数据结构与算法 最新文章
【力扣106】 从中序与后续遍历序列构造二叉
leetcode 322 零钱兑换
哈希的应用:海量数据处理
动态规划|最短Hamilton路径
华为机试_HJ41 称砝码【中等】【menset】【
【C与数据结构】——寒假提高每日练习Day1
基础算法——堆排序
2023王道数据结构线性表--单链表课后习题部
LeetCode 之 反转链表的一部分
【题解】lintcode必刷50题<有效的括号序列
上一篇文章      下一篇文章      查看所有文章
加:2021-07-31 16:53:22  更:2021-07-31 16:54:39 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/8 2:32:35-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码