文章目录

  • 关于 多元线性回归
  • 求解
  • 算法封装
    • 使用 sklearn 处理 boston 房价回归问题
  • 使用 kNN 解决多元线性回归问题

关于 多元线性回归

简单线性回归:假设样本只有一个特征值;
多元线性回归:解决 很多特征值 。


y^(i)=θ0+θ1X1(i)+θ2X2(i)+...+θnXn(i)\hat{y}^{(i)} = \theta_{0} + \theta_{1}X_1^{(i)} + \theta_{2}X_2^{(i)} + ... + \theta_{n}X_n^{(i)} y^​(i)=θ0​+θ1​X1(i)​+θ2​X2(i)​+...+θn​Xn(i)​


求解

目标:要找到 $ \theta_{0}, \theta_{1}, \theta_{2} … \theta_{n} $ 使得 目标函数(损失函数) ∑i=1m(y(i)−y^(i))2\sum_{i=1}^m ( y^{(i)} - \hat{y}^{(i)} )^2 i=1∑m​(y(i)−y^​(i))2 尽可能小

将上面多个 $ \theta $ 整理为一个元素,转置为 列向量。
θ=(θ0,θ1,θ2,...,θn)T\theta = (\theta_{0}, \theta_{1}, \theta_{2}, ... , \theta_{n} )^T θ=(θ0​,θ1​,θ2​,...,θn​)T

给 $ \theta_{0} $ 增加一个虚构的乘数 $ X_0^{(i) } \equiv 1$,得到:
y^(i)=θ0X0(i)+θ1X1(i)+θ2X2(i)+...+θnXn(i)\hat{y}^{(i)} = \theta_{0}X_0^{(i) } + \theta_{1}X_1^{(i)} + \theta_{2}X_2^{(i)} + ... + \theta_{n}X_n^{(i)} y^​(i)=θ0​X0(i)​+θ1​X1(i)​+θ2​X2(i)​+...+θn​Xn(i)​

X(i)=(X0(i),X1(i),X2(i),...,Xn(i))X^{(i)} = ( X_0^{(i)}, X_1^{(i)}, X_2^{(i)}, ... , X_n^{(i)} ) X(i)=(X0(i)​,X1(i)​,X2(i)​,...,Xn(i)​)

y^(i)=X(i)⋅θ\hat{y}^{(i)} = X^{(i)} \cdot \theta y^​(i)=X(i)⋅θ


将此推广到所有样本上

(1X1(1)X2(1)...Xn(1)1X1(2)X2(2)...Xn(2)...1X1(m)X2(m)...Xn(m))\left( \begin{array}{cc} 1 & X_1^{(1)} & X_2^{(1)} & ... & X_n^{(1)} \\ 1 & X_1^{(2)} & X_2^{(2)} & ... & X_n^{(2)} \\ ... \\ 1 & X_1^{(m)} & X_2^{(m)} & ... & X_n^{(m)} \end{array} \right) ⎝⎜⎜⎜⎛​11...1​X1(1)​X1(2)​X1(m)​​X2(1)​X2(2)​X2(m)​​.........​Xn(1)​Xn(2)​Xn(m)​​⎠⎟⎟⎟⎞​

比之前的 XXX 多了一列 1,为了区分,记作 $ X_b$


θ=(θ0θ1θ2...θn)\theta = \left( \begin{array}{cc} \theta_0 \\ \theta_1 \\ \theta_2 \\ ... \\ \theta_n \end{array} \right) θ=⎝⎜⎜⎜⎜⎛​θ0​θ1​θ2​...θn​​⎠⎟⎟⎟⎟⎞​

$ \theta_0 $ 称为截距 intercept,代表一个偏移;
$ \theta_1 - \theta_n $ 称为系数 coefficients;每一个都对应原来样本中的一个特征,用于描述这个特征 对于最终样本 相应的贡献程度;


y^=Xb⋅θ\hat{y} = X_b \cdot \thetay^​=Xb​⋅θ

所以目标函数也可以转化为:
(y−Xb⋅θ)T(y−Xb⋅θ)(y - X_b \cdot \theta)^T (y - X_b \cdot \theta) (y−Xb​⋅θ)T(y−Xb​⋅θ)

θ=(XbTXb)−1XbTy\theta = ( X_b^T X_b )^{-1} X_b^T y θ=(XbT​Xb​)−1XbT​y

这个式子称为 多元线性回归 的 正规方程解(Normal Equation )

优点:不需要对数据做归一化处理;
因为最后估计的 θ\thetaθ 是原始数据进行数学运算的结果,这种运算中 不存在量纲的问题, θ\thetaθ 是线性方程中每一个 x 前面的系数而已,没有量纲的问题。

缺点:时间复杂度比较高,大概是 O(n^3),即使使用优化方案,也在 O(n^2.4) 左右。
无论是样本量大,还是特征多,用这个方法都会很慢。所以一般使用其他方法。


算法封装

import numpy as np
from .metrics import r2_scoreclass LinearRegression:def __init__(self):"""初始化Linear Regression模型"""self.coef_ = Noneself.intercept_ = Noneself._theta = Nonedef 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((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 selfdef 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):try:return np.sum((y - X_b.dot(theta)) ** 2) / len(y)except:return float('inf')def dJ(theta, X_b, y):# 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(X_b)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.intercept_ = self._theta[0]self.coef_ = self._theta[1:]return selfdef 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 >= 1def dJ_sgd(theta, X_b_i, y_i):return X_b_i * (X_b_i.dot(theta) - y_i) * 2.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)for cur_iter in range(n_iters):indexes = np.random.permutation(m)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.intercept_ = self._theta[0]self.coef_ = self._theta[1:]return selfdef 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()"

使用 sklearn 处理 boston 房价回归问题

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasetsboston = datasets.load_boston()boston.keys()
# dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])boston.DESCR
# 有 13 个特征boston.feature_names
# array(['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT'], dtype='<U7')X = boston.data
y = boston.targetX = X[y < 50.0]
y = y[y < 50.0]from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42)from sklearn.linear_model import LinearRegressionreg = LinearRegression()reg.fit(X_train, y_train)
# LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)reg.coef_
'''array([-1.22096140e-01,  3.24934065e-02, -4.51945652e-02,  6.32525034e-02,-1.17444911e+01,  3.61793376e+00, -2.00394486e-02, -1.21059188e+00,2.47235697e-01, -1.31042159e-02, -8.35556922e-01,  8.18076684e-03,-3.81616606e-01])
'''reg.intercept_
# 32.73189970831903reg.score(X_test, y_test)
# 0.7640047258028569

使用 kNN 解决多元线性回归问题

from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
knn_reg = KNeighborsRegressor()
knn_reg.fit(X_train, y_train)
# KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=5, p=2, weights='uniform')knn_reg.score(X_test, y_test)
# 0.5812004118756823# 使用网格搜索寻找超参数
param_grid = [{'weights': ['uniform'],'n_neighbors': [i for i in range(1,11)]}, {'weights': ['distance'],'n_neighbors': [i for i in range(1,11)],'p': [i for i in range(1,6)]}]from sklearn.model_selection import GridSearchCV
# CV 的意思是 Cross Validation,交叉验证。grid_search = GridSearchCV(knn_reg, param_grid, n_jobs=-1, verbose=2)%time
grid_search.fit(X_train, y_train)'''CPU times: user 2 µs, sys: 1e+03 ns, total: 3 µsWall time: 4.77 µsFitting 3 folds for each of 60 candidates, totalling 180 fitsGridSearchCV(cv='warn', error_score='raise-deprecating',estimator=KNeighborsRegressor(algorithm='auto', leaf_size=30,metric='minkowski',metric_params=None, n_jobs=None,n_neighbors=5, p=2,weights='uniform'),iid='warn', n_jobs=-1,param_grid=[{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],'weights': ['uniform']},{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],'p': [1, 2, 3, 4, 5], 'weights': ['distance']}],pre_dispatch='2*n_jobs', refit=True, return_train_score=False,scoring=None, verbose=2)'''grid_search.best_params_
# {'n_neighbors': 10, 'p': 1, 'weights': 'distance'}grid_search.best_score_
# 0.6343537550346618grid_search.best_estimator_
# KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=10, p=1, weights='distance')grid_search.best_estimator_.score(X_test, y_test)
# 比 knn 默认的结果,但是不如线性回归的效果。但这里的score 标准,可能和 lr 中的标准不通过。
# 0.6717251762406973

ML - 多元线性回归相关推荐

  1. ML之MLiR:利用多元线性回归法,从大量数据(csv文件)中提取五个因变量(输入运输任务总里程数、运输次数、三种不同的车型,预测需要花费的小时数)来预测一个自变量

    ML之MLiR:利用多元线性回归法,从大量数据(csv文件)中提取五个因变量(输入运输任务总里程数.运输次数.三种不同的车型,预测需要花费的小时数)来预测一个自变量 输出结果 代码设计 from nu ...

  2. 09机器学习实战之多元线性回归

    基本概念 1. 与简单线性回归区别(simple linear regression) 多个自变量(x) 2. 多元回归模型 y=β0+β1x1+β2x2+ ... +βpxp+ε 其中:β0,β1, ...

  3. 【Python-ML】SKlearn库多元线性回归性能评估

    # -*- coding: utf-8 -*- ''' Created on 2018年1月24日 @author: Jason.F @summary: 有监督回归学习-多元线性回归的性能评估 ''' ...

  4. android 揭示动画_遗传编程揭示具有相互作用的多元线性回归

    android 揭示动画 We all had some sort of experience with linear regression. It's one of the most used re ...

  5. 机器学习多元线性回归_过度简化的机器学习(1):多元回归

    机器学习多元线性回归 The term machine learning may sound provocative. Machines do not learn like humans do. Ho ...

  6. python多元线性回归代码_Python实现梯度下降算法求多元线性回归(一)

    预备知识及相关文档博客 学习吴恩达机器学习课程笔记,并用python实现算法 python numpy基本教程: numpy相关教程 数据来自于UCI的机器学习数据库: UCI的机器学习数据库 pyt ...

  7. R语言——多元线性回归

    1.多元线性回归模型 1.1多元回归模型与多元回归方程 设因变量为y,k个自变量分别为,描述因变量y如何依赖于自变量和误差项ε的方程称为多元回归模型.其一般形式可表示为: 式中,为模型的参数,ε为随机 ...

  8. 【统计学习系列】多元线性回归模型(三)——参数估计量的性质

    文章目录 1. 前文回顾 2. 衡量参数估计量好坏的指标 2.1 无偏性 2.2 一致性 2.3 有效性 3. 一些引理(可略) 3.1 期望运算的线性性 3.2 协方差运算的半线性性 3.3 矩阵迹 ...

  9. Stata的多元线性回归与泊松回归

    1. 相关性检测 Pearson相关系数 correlate [varlist] [if] [in] [weight] [, correlate_options] Spearman相关系数 pwcor ...

最新文章

  1. Java中BASE64 编码
  2. ACMNO.2 输入一个华氏温度,要求输出摄氏温度。公式为 c=5(F-32)/9 输出要求有文字说明,取位2小数。 输入 一个华氏温度,浮点数 输出 摄氏温度,浮点两位小数
  3. RH033 Unit 2 Linux Usage Basics
  4. who whoami who am i的区别
  5. 一文读懂文本处理中的对抗训练
  6. Linux 下wifi 驱动开发(四)—— USB接口WiFi驱动浅析
  7. 前端:JS/25/DOM官方定义,DOM分类,HTML节点树(节点关系,节点类型,),核心DOM中公共的属性和方法(节点访问,查找DOM节点,节点属性,节点的创建,追加和删除)
  8. 补习系列(16)-springboot mongodb 数据库应用技巧
  9. oracle数据库备份和还原
  10. Python基础(while循环/赋值运算符)
  11. AI 六十年,强人工智能何时到来?
  12. Mysql 大量数据快速导出
  13. 错过了蓝月亮,你还有我们~~只此一次!
  14. 6. NMF方法及实例
  15. Excel合并两列数据到一列中并以逗号隔开的处理方式
  16. Docker 极简入门指南
  17. 微信小程序申请发布流程
  18. 今天美国大学计算机硕士放榜吗,美国大学研究生offer放榜时间一般是什么时候?别错过哟!...
  19. 【OpenGL】OpenGL帧缓存对象(FBO:Frame Buffer Object)
  20. “深入理解计算机系统”小组学习的Task01-学习日志

热门文章

  1. 按半字寻址是什么意思?
  2. 【对分法求解非线性方程的实根】
  3. java图片转单色位图_如何将黑白图保存为单色位图
  4. 2020年聚合支付评级结果及如何开展评级工作经验分享
  5. 教你查看网页记住的密码
  6. Wine是什么-Wine能什么-Wine 工作原理
  7. 大数据、AI...从概念到落地,数据智能践行者-袋鼠云有话说 | 附沙龙视频
  8. javascript事件循环Event Loop,宏任务与微任务
  9. 工业组态人机界面与嵌入式工业平板电脑的区别
  10. 大数据项目之电商数仓(用户行为数据采集)