01_线性回归

线性回归

  • 1 一元线性回归重要公式
  • 2 一元线性回归code实现
  • 3 sklearn实现一元线性回归
  • 4 多元线性回归公式
  • 5 sklearn实现多元线性回归
  • 6 模型评价指标
  • 7 多项式回归
    • 7.1将多项式回归作为线性回归处理
    • 7.2 sklaearn多项式特征维度扩展

1 一元线性回归重要公式

一元线性回归的均方误差:
E ( w , b ) = ∑ i = 1 m ( y i − w x i − b ) 2 {{\rm{E}}_{(w,b)}} = {\sum\limits_{i = 1}^m {({y_i} - w{x_i} - b)} ^2} E(w,b)=i=1m(yiwxib)2
对w和b分别求导,得
∂ E ( w , b ) ∂ w = 2 ( w ∑ i = 1 m x i 2 − ∑ i = 1 m ( y i − b ) x i ) \frac{{\partial {E_{(w,b)}}}}{{\partial w}} = 2(w\sum\limits_{i = 1}^m {x_i^2 - \sum\limits_{i = 1}^m {({y_i} - b){x_i}} } ) wE(w,b)=2(wi=1mxi2i=1m(yib)xi)
∂ E ( w , b ) ∂ b = 2 ( m b − ∑ i = 1 m y i − w x i ) \frac{{\partial {E_{(w,b)}}}}{{\partial b}} = 2(mb - \sum\limits_{i = 1}^m {{y_i} - w{x_i}} ) bE(w,b)=2(mbi=1myiwxi)
令以上式子分别等于0,得
w = ∑ i = 1 m y i ( x i − x ˉ ) ∑ i = 1 m x i 2 − 1 m ( ∑ i = 1 m x i ) 2 w = \frac{{\sum\limits_{i = 1}^m {{y_i}({x_i} - \bar x)} }}{{\sum\limits_{i = 1}^m {x_i^2 - \frac{1}{m}{{(\sum\limits_{i = 1}^m {{x_i}} )}^2}} }} w=i=1mxi2m1(i=1mxi)2i=1myi(xixˉ)

b = 1 m ∑ i = 1 m ( y i − w x i ) b = \frac{1}{m}\sum\limits_{i = 1}^m {({y_i} - w{x_i})} b=m1i=1m(yiwxi)

如果用Python 来实现上式的话,上式中的求和运算只能用循环来实现。但是如果能将上式向量化,也就是转换成矩阵(即向量)运算的话,就可以利用诸如NumPy 这种专门加速矩阵运算的类库来进
行编写。
w = ∑ i = 1 m ( x i − x ˉ ) ( y i − y ˉ ) ∑ i = 1 m ( x i − x ˉ ) w = \frac{{\sum\limits_{i = 1}^m {({x_i} - \bar x)({y_i} - \bar y)} }}{{\sum\limits_{i = 1}^m {({x_i} - \bar x)} }} w=i=1m(xixˉ)i=1m(xixˉ)(yiyˉ)

2 一元线性回归code实现

import numpy as np
import pandas as pd
from sklearn import datasets
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")# 该数据集的导入可参考 https://blog.csdn.net/virtualxiaoman/article/details/133844179
# 数据集的具体样式及为什么跳过前22行,参考http://lib.stat.cmu.edu/datasets/boston
# 该数据集各变量描述
'''Variables in order:CRIM     per capita crime rate by townZN       proportion of residential land zoned for lots over 25,000 sq.ft.INDUS    proportion of non-retail business acres per townCHAS     Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)NOX      nitric oxides concentration (parts per 10 million)RM       average number of rooms per dwellingAGE      proportion of owner-occupied units built prior to 1940DIS      weighted distances to five Boston employment centresRAD      index of accessibility to radial highwaysTAX      full-value property-tax rate per $10,000PTRATIO  pupil-teacher ratio by townB        1000(Bk - 0.63)^2 where Bk is the proportion of blacks by townLSTAT    % lower status of the populationMEDV     Median value of owner-occupied homes in $1000's
'''
data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x = data[:, 5]
y = targetx = x[y<50]     # 该列数据的最大值是50,不移除的话会存在很多等于50的数据
y = y[y<50]plt.figure(num='Figure1')
plt.scatter(x,y)
plt.show()from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)
plt.figure(num='Figure2')
plt.scatter(x_train, y_train)
plt.show()def fit(x, y):a_up = np.sum((x-np.mean(x))*(y - np.mean(y)))a_bottom = np.sum((x-np.mean(x))**2)a = a_up / a_bottomb = np.mean(y) - a * np.mean(x)return a, ba, b = fit(x_train, y_train)
plt.figure(num='Figure3')
plt.scatter(x_train, y_train)
plt.plot(x_train, a*x_train+ b, c='r')
plt.show()plt.figure(num='Figure4')
plt.scatter(x_test, y_test)
plt.plot(x_test, a*x_test+ b, c='r')
plt.show()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3 sklearn实现一元线性回归

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegressiondata_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x = data[:, 5]
y = target
x = x[y<50]     # 该列数据的最大值是50,不移除的话会存在很多等于50的数据
y = y[y<50]lin_reg = LinearRegression()
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)
lin_reg.fit(x_train.reshape(-1,1), y_train)
y_predict = lin_reg.predict(x_test.reshape(-1,1))
plt.scatter(x_test, y_test)
plt.plot(x_test, y_predict, c='r')
plt.show()# 获取相关参数:
# 斜率(coefficient):使用coef_属性
# 截距(intercept):使用intercept_属性
slope = lin_reg.coef_[0]
intercept = lin_reg.intercept_# 输出线性回归模型的斜率和截距,和回归方程式
print("斜率(coefficient):", slope)
print("截距(intercept):", intercept)
print(f'回归(拟合)方程式为: y={slope:.1f}*x + {intercept:.1f}')

在这里插入图片描述
斜率(coefficient): 8.056822140369604
截距(intercept): -28.493068724477876
回归(拟合)方程式为: y=8.1*x + -28.5

4 多元线性回归公式

在这里插入图片描述
w ^ ∗ = ( X T X ) − 1 X T y {\hat w^*} = {({X^{\rm T}}X)^{ - 1}}{X^{\rm T}}y w^=(XTX)1XTy

5 sklearn实现多元线性回归

注,线性回归中不需要归一化;sklearn实现的线性回归并非是4中的方法

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegressiondata_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x = data
y = target
x = x[y<50]     # 该列数据的最大值是50,不移除的话会存在很多等于50的数据
y = y[y<50]lin_reg = LinearRegression()
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state = 0)
lin_reg.fit(x_train, y_train)
y_predict = lin_reg.predict(x_test)
score = lin_reg.score(x_test, y_test)
print("score:", score)# 获取相关参数:
# 斜率(coefficient):使用coef_属性
# 截距(intercept):使用intercept_属性
slope = lin_reg.coef_[0]
intercept = lin_reg.intercept_
# 输出线性回归模型的斜率和截距,和回归方程式
print("coefficient:", slope)
print("intercept:", intercept)## 对比归一化后的效果
from sklearn.preprocessing import StandardScaler
standardScaler = StandardScaler()
standardScaler.fit(x_train)
x_train = standardScaler.transform(x_train)
x_test = standardScaler.transform(x_test)
lin_reg.fit(x_train, y_train)
score2 = lin_reg.score(x_test, y_test)
print("score2:", score)

score: 0.7455942658788959
coefficient: -0.12265382712227257
intercept: 35.07476409245881
score2: 0.7455942658788959

6 模型评价指标

M S E = 1 n ∑ i = 1 n ( y r e a l − y p r e d i c t ) 2 MSE = \frac{1}{n}\sum\limits_{i = 1}^n {{{({y_{real}} - {y_{predict}})}^2}} MSE=n1i=1n(yrealypredict)2
R M S E = 1 n ∑ i = 1 n ( y r e a l − y p r e d i c t ) 2 RMSE = \sqrt {\frac{1}{n}\sum\limits_{i = 1}^n {{{({y_{real}} - {y_{predict}})}^2}} } RMSE=n1i=1n(yrealypredict)2
M A E = 1 n ∣ y r e a l − y p r e d i c t ∣ MAE = \frac{1}{n}\left| {{y_{real}} - {y_{predict}}} \right| MAE=n1yrealypredict
R 2 = 1 − ∑ ( y r e a l − y p r e d i c t ) 2 ∑ ( y r e a l − y ˉ r e a l ) 2 = 1 − 1 n ∑ ( y r e a l − y p r e d i c t ) 2 1 n ( y r e a l − y ˉ r e a l ) 2 = 1 − M S E v a r ( y r e a l ) {R^2} = 1 - \frac{{\sum {{{({y_{real}} - {y_{predict}})}^2}} }}{{\sum {{{({y_{real}} - {{\bar y}_{real}})}^2}} }} = 1 - \frac{{\frac{1}{n}\sum {{{({y_{real}} - {y_{predict}})}^2}} }}{{\frac{1}{n}{{({y_{real}} - {{\bar y}_{real}})}^2}}} = 1 - \frac{{MSE}}{{{\mathop{\rm var}} ({y_{real}})}} R2=1(yrealyˉreal)2(yrealypredict)2=1n1(yrealyˉreal)2n1(yrealypredict)2=1var(yreal)MSE

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import warnings
warnings.filterwarnings("ignore")data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x = data[:, -1].reshape(-1, 1)
y = target.reshape(-1, 1)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)linearReg = LinearRegression()
model = linearReg.fit(x_train, y_train)
y_predict = model.predict(x_test)
plt.figure(num='Figure6')
plt.scatter(x_test, y_test, s=10)
plt.plot(x_test, y_predict, c='r')
plt.show()y_real = y_test
# MSE
mse = np.sum((y_real - y_predict) ** 2) / len(y_test)
# RMSE
rmse = np.sqrt(mse)
# MAE
mae = np.sum(np.abs(y_real - y_predict)) / len(y_test)
# R2
r2 = 1 - (np.sum((y_real - y_predict) ** 2)) / (np.sum((y_real - np.mean(y_real)) ** 2))
r2_1 = 1 - mse / np.var(y_real)
print(f'MSE={mse:.1f}')
print(f'RMSE={rmse:.1f}')
print(f'MAE={mae:.1f}')
print(f'R2={r2:.3f}')
print(f'R2_1={r2_1:.3f}')

在这里插入图片描述
MSE=39.8
RMSE=6.3
MAE=4.5
R2=0.522
R2_1=0.522
上述评价指标也可用直接调用sklearn

# 接上面代码块
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import r2_score# MSE
mse = mean_squared_error(y_real, y_predict)
# RMSE
rmse = mean_squared_error(y_real, y_predict, squared=False)
# MAE
mae = mean_absolute_error(y_real, y_predict)
# R2
r2 = r2_score(y_real, y_predict)
r2_1 = model.score(x_test, y_test)
print(f'MSE={mse:.1f}')
print(f'RMSE={rmse:.1f}')
print(f'MAE={mae:.1f}')
print(f'R2={r2:.3f}')
print(f'R2_1={r2_1:.3f}')

MSE=39.8
RMSE=6.3
MAE=4.5
R2=0.522
R2_1=0.522
回归模型中,损失函数一般使用MSE、RMSE、MAE,而性能评价指标多使用R2。

7 多项式回归

7.1将多项式回归作为线性回归处理

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegressionx = np.random.uniform(-4, 2, size=(100))
y = 2 * x ** 2 + 4 * x + 3 + np.random.randn(100)
X = x.reshape(-1, 1)
X_new = np.hstack([X, X ** 2])
linear_regression = LinearRegression()
linear_regression.fit(X_new, y)
y_predict = linear_regression.predict(X_new)
plt.scatter(x, y)
plt.plot(np.sort(x), y_predict[np.argsort(x)], color="red")
plt.show()# 输出线性回归模型的斜率和截距,和回归方程式
print("coefficient", linear_regression.coef_)
print("intercept", linear_regression.intercept_)

在这里插入图片描述
coefficient [3.84064494 1.9612757 ]
intercept 3.0225282289137976

7.2 sklaearn多项式特征维度扩展

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegressionx = np.random.uniform(-4, 2, size=(100))
y = 2 * x ** 2 + 4 * x + 3 + np.random.randn(100)
X = x.reshape(-1, 1)
polynomial_features = PolynomialFeatures(degree=2)
X_poly = polynomial_features.fit_transform(X)   # 二次多项式特征维度扩展
print(X_poly[:3])linear_regression = LinearRegression()
linear_regression.fit(X_poly, y)
y_predict = linear_regression.predict(X_poly)
plt.scatter(x, y)
plt.plot(np.sort(x), y_predict[np.argsort(x)], color="red")
plt.show()# 输出线性回归模型的斜率和截距,和回归方程式
print("coefficient", linear_regression.coef_)
print("intercept", linear_regression.intercept_)

在这里插入图片描述
[[ 1. -0.61108249 0.37342182]
[ 1. 0.70522585 0.4973435 ]
[ 1. -0.84277066 0.71026238]]
coefficient [0. 3.9052941 1.96796747]
intercept 3.056164951792293

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/2871142.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

谁将主导未来AI市场?Claude3、Gemini、Sora与GPT-4的技术比拼

【最新增加Claude3、Gemini、Sora、GPTs讲解及AI领域中的集中大模型的最新技术】 2023年随着OpenAI开发者大会的召开&#xff0c;最重磅更新当属GPTs&#xff0c;多模态API&#xff0c;未来自定义专属的GPT。微软创始人比尔盖茨称ChatGPT的出现有着重大历史意义&#xff0c;不亚…

微信开发者工具如何使用?使用注意事项

&#xff08;1&#xff09;单位如何进行换算&#xff1f; 1 px 750/屏幕宽度 rpx 1 rpx 屏幕宽度/750 px &#xff08;2&#xff09;如何新建文件&#xff1f; 1> 点开app.json 2> 在“pages/index/index”后面接“&#xff0c;pages/自定义文件夹名/自定义文件名”…

怎么在空闲时间用网络赚钱且收入不低于50?

何其有幸&#xff0c;我们生活在一个网络时代&#xff0c;买东西&#xff0c;生活缴费都可以通过网络来完成&#xff0c;给大家省下了大量的时间和精力&#xff0c;让生活更加便利。不仅如此&#xff0c;还可以通过网络来娱乐、交流&#xff0c;更可以通过它来赚钱。很多朋友上…

网络编程--高并发服务器

这里写目录标题 引入场景 多进程并发服务器二级目录二级目录二级目录 多线程并发服务器二级目录二级目录二级目录 多路IO转接服务器设计思路对比引入 select函数简介参数介绍第一个参数第234参数返回值对于第234参数的应用对于最后一个参数总结 epoll进阶二级目录二级目录二级目…

跳绳计数,YOLOV8POSE

跳绳计数&#xff0c;YOLOV8POSE 通过计算腰部跟最初位置的上下波动&#xff0c;计算跳绳的次数

栈和队列(Java实现)

栈和队列&#xff08;Java实现&#xff09; 栈 栈(Stack)&#xff1a;栈是先进后出&#xff08;FILO, First In Last Out&#xff09;的数据结构。Java中实现栈有以下两种方式&#xff1a; stack类LinkedList实现&#xff08;继承了Deque接口&#xff09; &#xff08;1&am…

【C语言入门】浮点型数据在内存中的存储

✨✨欢迎大家来到Celia的博客✨✨ &#x1f389;&#x1f389;创作不易&#xff0c;请点赞关注&#xff0c;多多支持哦&#x1f389;&#x1f389; 所属专栏&#xff1a;C语言 个人主页&#xff1a;Celias blog~ 目录 ​编辑 引言 引例 一、浮点型在内存中的存储方式 1.1 …

Linux 时间系统调用

UNIX及LinuxQ的时间系统是由「新纪元时间」Epoch开始计算起。Epoch是指定为1970年1月1日凌晨零点零分零秒&#xff0c;格林威治时间。目前大部份的UNX系统都是用32位来记录时间&#xff0c;正值表示为1970以后&#xff0c;负值则表示1970年以前。 对于当前时间到Epoch 我们用两…

2024蓝桥杯每日一题(DFS)

备战2024年蓝桥杯 -- 每日一题 Python大学A组 试题一&#xff1a;奶牛选美 试题二&#xff1a;树的重心 试题三&#xff1a;大臣的差旅费 试题四&#xff1a;扫雷 试题一&#xff1a;奶牛选美 【题目描述】 听说最近两斑点的奶牛最受欢迎&#xff0c;…

后端系统开发之——创建SpringBoot工程

原文地址&#xff1a;后端框架系统开发之——创建SpringBoot工程 - Pleasure的博客 下面是正文内容&#xff1a; 前言 现在的市场环境&#xff0c;如果你单单只是作为前端工程师或者是后端工程师&#xff0c;在开发Web应用的时候都需要去读取企业提供的接口文档。而当你前后端…

没想到打脸这么快,AI程序员已经出发了!

大家好啊&#xff0c;我是豆小匠。 先介绍一下本期的主角&#xff1a;Devin&#xff0c;世界上第一位AI程序员&#xff0c;由2023年11月成立的10人初创公司Cognition AI开发。 1. AI程序员已经能做到什么程度 3月13日&#xff0c;Cognition AI公司在X平台&#xff08;原推特&…

关于volatile与指令重排序的探讨

写在开头 在之前的学习我们了解到&#xff0c;为了充分利用缓存&#xff0c;提高程序的执行速度&#xff0c;编译器在底层执行的时候&#xff0c;会进行指令重排序的优化操作&#xff0c;但这种优化&#xff0c;在有些时候会带来 有序性 的问题。 那何为有序性呢&#xff1f;…

LeetCode Python - 57. 插入区间

目录 题目描述解法方法一&#xff1a;排序 区间合并方法二&#xff1a;一次遍历 运行结果方法一&#xff1a;排序 区间合并方法二&#xff1a;一次遍历 题目描述 给你一个 无重叠的 &#xff0c;按照区间起始端点排序的区间列表。 在列表中插入一个新的区间&#xff0c;你需…

MySQL语法分类 DQL(1)基础查询

//语法 select 字段列表 from 表名列表 where条件列表 group by分组字段 having 分组后的条件 order by排序 limit 分页限定为了更好的学习这里给出基本表数据用于查询操作 create table student (id int, name varchar(20), age int, sex varchar(5),address varchar(100),ma…

数据的响应式:实现动态数据驱动的技巧

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

rt-thread之通讯协议modbus软件包的使用记录(lwip+modbus组合)

前言 使用freemodbus软件包使用网口通讯(sallwip)ip地址使用dhcp动态获取 软件包 相关宏定义 /*-----------------------------------------NET 宏定义-------------------------------------------*/#define RT_USING_SAL #define SAL_INTERNET_CHECK /* Docking with prot…

App拉新必备!Xinstall渠道追踪,让每一分钱都花在刀刃上

在移动互联网时代&#xff0c;App已经成为人们日常生活中不可或缺的一部分。然而&#xff0c;对于App开发者来说&#xff0c;如何有效地进行拉新&#xff0c;提高用户留存率&#xff0c;一直是一个难题。而渠道追踪&#xff0c;作为App推广过程中的重要环节&#xff0c;往往被忽…

Prometheus + Grafana 监控解决方案介绍及部署

Prometheus Grafana 监控解决方案介绍 Prometheus&#xff08;普罗米修斯&#xff09;是一套开源的 监控&报警&时间序列 数据库 的组合&#xff0c;起始是由SoundCloud公司开发。 随着发展&#xff0c;越来越多公司和组织接受采用Prometheus&#xff0c;社区也十分活…

【Spark编程基础】RDD 编程初级实践(附源代码)

目录 一、实验目的二、实验平台三、实验内容1.spark-shell 交互式编程2.编写独立应用程序实现数据去重3.编写独立应用程序实现求平均值问题 一、实验目的 1、熟悉 Spark 的 RDD 基本操作及键值对操作&#xff1b; 2、熟悉使用 RDD 编程解决实际具体问题的方法 二、实验平台 …

【LabVIEW FPGA入门】浮点数类型支持

如今&#xff0c;使用浮点运算来设计嵌入式系统的需求变得越来越普遍。随着 FPGA 因其固有的大规模并行性而在浮点性能方面继续超越微处理器&#xff0c;这种情况正在加剧。线性代数和数字信号处理 (DSP) 等高级算法可以受益于浮点数据类型的高动态范围精度。LabVIEW FPGA 通过…