数据分析中经常会使用到数据拟合,本文中将阐述如何实现一元以及多元的线性拟合以及多项式拟合,本文中只涉及实现方式,不涉及理论知识。

模型拟合中涉及的误差评估方法如下所示:

import numpy as np
def stdError_func(y_test, y):return np.sqrt(np.mean((y_test - y) ** 2))def R2_1_func(y_test, y):return 1 - ((y_test - y) ** 2).sum() / ((y.mean() - y) ** 2).sum()def R2_2_func(y_test, y):y_mean = np.array(y)y_mean[:] = y.mean()return 1 - stdError_func(y_test, y) / stdError_func(y_mean, y)

一元线性拟合

import pandas as pd
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_modelfilename = "E:/data.csv"
df= pd.read_csv(filename)
x = np.array(df.iloc[:,0].values)y = np.array(df.iloc[:,5].values)cft = linear_model.LinearRegression()
cft.fit(x[:,np.newaxis], y) #模型将x变成二维的形式, 输入的x的维度为[None, 1]print("model coefficients", cft.coef_)
print("model intercept", cft.intercept_)predict_y =  cft.predict(x[:,np.newaxis])
strError = stdError_func(predict_y, y)
R2_1 = R2_1_func(predict_y, y)
R2_2 = R2_2_func(predict_y, y)
score = cft.score(x[:,np.newaxis], y) ##sklearn中自带的模型评估,与R2_1逻辑相同print(' strError={:.2f}, R2_1={:.2f},  R2_2={:.2f}, clf.score={:.2f}'.format(strError,R2_1,R2_2,score))

结果输出为:
model coefficients [-31.2375]
model intercept 7.415750000000001
strError=1.11, R2_1=0.28, R2_2=0.15, clf.score=0.28

模型拟合的表达式为:
y = 7.415750000000001 +(-31.2375) * x
从拟合的均方误差和得分来看效果不佳

多元线性拟合

 import pandas as pd
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_modelfilename = "E:/data.csv"
df= pd.read_csv(filename)
x = np.array(df.iloc[:,0:4].values)y = np.array(df.iloc[:,5].values)cft = linear_model.LinearRegression()
print(x.shape)
cft.fit(x, y) #print("model coefficients", cft.coef_)
print("model intercept", cft.intercept_)predict_y =  cft.predict(x)
strError = stdError_func(predict_y, y)
R2_1 = R2_1_func(predict_y, y)
R2_2 = R2_2_func(predict_y, y)
score = cft.score(x, y) ##sklearn中自带的模型评估,与R2_1逻辑相同print('strError={:.2f}, R2_1={:.2f},  R2_2={:.2f}, clf.score={:.2f}'.format(strError,R2_1,R2_2,score))

结果输出为:
model coefficients [-31.2375 17.74375 44.325 5.7375 ]
model intercept 0.5051249999999978
strError=0.58, R2_1=0.80, R2_2=0.56, clf.score=0.80

模型拟合的表达式为:
y = 0.5051249999999978 +(-31.2375) * x11 + 17.74375 *x2 + 44.325 * x3 + 5.7375 * x4
从拟合的均方误差和得分来看在之前的基础上有所提升

一元多项式拟合

以三次多项式为例

import pandas as pd
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_modelfilename = "E:/data.csv"
df= pd.read_csv(filename)
x = np.array(df.iloc[:,0].values)y = np.array(df.iloc[:,5].values)poly_reg =PolynomialFeatures(degree=3) #三次多项式
X_ploy =poly_reg.fit_transform(x[:, np.newaxis])
print(X_ploy.shape)
lin_reg_2=linear_model.LinearRegression()
lin_reg_2.fit(X_ploy,y)
predict_y =  lin_reg_2.predict(X_ploy)
strError = stdError_func(predict_y, y)
R2_1 = R2_1_func(predict_y, y)
R2_2 = R2_2_func(predict_y, y)
score = lin_reg_2.score(X_ploy, y) ##sklearn中自带的模型评估,与R2_1逻辑相同print("model coefficients", lin_reg_2.coef_)
print("model intercept", lin_reg_2.intercept_)
print('degree={}: strError={:.2f}, R2_1={:.2f},  R2_2={:.2f}, clf.score={:.2f}'.format(3, strError,R2_1,R2_2,score))

输出结果
model coefficients [ 0. 990.64583333 -11906.25 44635.41666667]
model intercept -20.724999999999117
degree=3: strError=1.08, R2_1=0.32, R2_2=0.17, clf.score=0.32

对应的函数表达式为 -20.724999999999117 + [0, 990.64583333, -11906.25, 44635.41666667] *[1, x, x^2, x.^3].T = -20.724999999999117 + 990.64583333 * x + ( -11906.25) * x^2 + 44635.41666667 * x^3

多元多项式拟合

import pandas as pd
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_modelfilename = "E:/data.csv"
df= pd.read_csv(filename)
x = np.array(df.iloc[:,0:4].values)y = np.array(df.iloc[:,5].values)poly_reg =PolynomialFeatures(degree=2) #三次多项式
X_ploy =poly_reg.fit_transform(x)
lin_reg_2=linear_model.LinearRegression()
lin_reg_2.fit(X_ploy,y)
predict_y =  lin_reg_2.predict(X_ploy)
strError = stdError_func(predict_y, y)
R2_1 = R2_1_func(predict_y, y)
R2_2 = R2_2_func(predict_y, y)
score = lin_reg_2.score(X_ploy, y) ##sklearn中自带的模型评估,与R2_1逻辑相同print("coefficients", lin_reg_2.coef_)
print("intercept", lin_reg_2.intercept_)
print('degree={}: strError={:.2f}, R2_1={:.2f},  R2_2={:.2f}, clf.score={:.2f}'.format(3, strError,R2_1,R2_2,score))

函数输出结果为:

coefficients [ 0. 332.28129937 -19.9240981 -9.10607925
-191.05593023 -287.93919929 -912.11402936 -1230.21922184
-207.90033986 99.03441748 190.26204994 433.25169929
273.13674555 257.66550523 344.92652936]
intercept 4.35175537840722
degree=3: strError=0.23, R2_1=0.97, R2_2=0.82, clf.score=0.97

代码中输入的自变量是一个包含四个变量的输入, 对应coefficients输出的是长度为15的向量, 其中对应到的变量分别为 variable_X = [1, x1, x2, x3, x4, x 1 ∗ x 1 x1*x1 x1∗x1, x 1 ∗ x 2 x1*x2 x1∗x2, x 1 ∗ x 3 x1*x3 x1∗x3, x 1 ∗ x 4 x1*x4 x1∗x4, x 2 ∗ x 2 x2*x2 x2∗x2, x 2 ∗ x 3 x2*x3 x2∗x3, x 2 ∗ x 4 x2*x4 x2∗x4, x 3 ∗ x 3 x3*x3 x3∗x3, x 3 ∗ x 4 x3*x4 x3∗x4, x 4 ∗ x 4 x4*x4 x4∗x4]

对应的方程式为: i n t e r c e p t + c o e f f i c i e n t s ∗ v a r i a b l e X . T intercept + coefficients * variable_X.T intercept+coefficients∗variableX​.T

代码中涉及到的数据集如下:

a,b,c,d,e
0.06,0.2,0.02,0.1,0.340
0.1,0.28,0.02,0.14,0.370
0.12,0.32,0.02,0.16,0.377
0.08,0.24,0.02,0.12,0.383
0.08,0.32,0.04,0.1,0.383
0.12,0.28,0.03,0.1,0.393
0.1,0.24,0.05,0.1,0.385
0.06,0.32,0.05,0.14,0.362
0.12,0.2,0.05,0.12,0.320
0.06,0.28,0.04,0.12,0.393
0.08,0.28,0.05,0.16,0.402
0.08,0.2,0.03,0.14,0.349
0.1,0.2,0.04,0.16,0.335
0.1,0.32,0.03,0.12,0.387
0.12,0.24,0.04,0.14,0.390
0.06,0.24,0.03,0.16,0.315

指数函数和幂函数拟合参照网址:
https://blog.csdn.net/kl28978113/article/details/88818885
参考链接:
https://blog.csdn.
net/weixin_44794704/article/details/89246032
https://blog.csdn.net/bxg1065283526/article/details/80043049
https://www.cnblogs.com/Lin-Yi/p/8975638.html

python实现多元线性拟合、一元多项式拟合、多元多项式拟合相关推荐

  1. Python实现多元线性回归方程梯度下降法与求函数极值

    梯度下降法 梯度下降法的基本思想可以类比为一个下山的过程. 假设这样一个场景:一个人被困在山上,需要从山上下来(找到山的最低点,也就是山谷).但此时山上的浓雾很大,导致可视度很低:因此,下山的路径就无 ...

  2. 基于Python的多元线性回归分析

    一.多元线性回归分析(Multiple regression) 1.与简单线性回归相比较,具有多个自变量x 2.多元回归模型 其中是误差值,与简单线性回归分析中的要求特点相一致.其余的系数和截距为参数 ...

  3. 用Python进行多元线性回归分析(附代码)

    https://developer.51cto.com/art/202008/624683.htm 很多人在做数据分析时会经常用到一元线性回归,这是描述两个变量间统计关系的最简单的回归模型.但现实问题 ...

  4. Python 实现多元线性回归预测

    一.二元输入特征线性回归 测试数据为:ex1data2.txt 2104,3,399900 1600,3,329900 2400,3,369000 1416,2,232000 3000,4,53990 ...

  5. Python 散点图线性拟合_机器学习之利用Python进行简单线性回归分析

    前言:在利用机器学习方法进行数据分析时经常要了解变量的相关性,有时还需要对变量进行回归分析.本文首先对人工智能/机器学习/深度学习.相关分析/因果分析/回归分析等易混淆的概念进行区分,最后结合案例介绍 ...

  6. Python小白的数学建模课-23.数据拟合全集

    拟合是用一个连续函数(曲线)靠近给定的离散数据,使其与给定的数据相吻合. 数据拟合的算法相对比较简单,但调用不同工具和方法时的函数定义和参数设置有所差异,往往使小白感到困惑. 本文基于 Scipy 工 ...

  7. 基于jupyter notebook的python编程-----利用梯度下降算法求解多元线性回归方程,并与最小二乘法求解进行精度对比

    基于jupyter notebook的python编程-----利用梯度下降算法求解多元线性回归方程,并与最小二乘法求解进行精度对比目录 一.梯度下降算法的基本原理 1.梯度下降算法的基本原理 二.题 ...

  8. python散点图拟合曲线-python散点图:如何添加拟合线并显示拟合方程与R方?

    原标题:python散点图:如何添加拟合线并显示拟合方程与R方? polyfit()函数可以使用最小二乘法将一些点拟合成一条曲线. numpy.polyfit(x, y, deg, rcond=Non ...

  9. 过拟合解决方法python_《python深度学习》笔记---4.4、过拟合与欠拟合(解决过拟合常见方法)...

    <python深度学习>笔记---4.4.过拟合与欠拟合(解决过拟合常见方法) 一.总结 一句话总结: 减小网络大小 添加权重正则化 添加 dropout 正则化 1.机器学习的根本问题? ...

最新文章

  1. mapreduce编程实例python-使用Python语言写Hadoop MapReduce程序
  2. android onpause时动画出错,Android生命周期之onPauseonStop
  3. 敏捷开发方法学及应用
  4. matlab hashset,MATLAB集合操作
  5. python函数式编程思想_python函数式编程
  6. 萌新向Python数据分析及数据挖掘 第二章 pandas 第二节 Python Language Basics, IPython, and Jupyter Notebooks...
  7. 一个没有担当的领导,通常会有哪些表现?
  8. NoSQL数据库介绍
  9. php实现豆瓣isbn查询API接口制作
  10. python四分位数_四分位数计算以及使用pandas计算
  11. 【错误率、精度、查准率、查全率和F1度量】详细介绍
  12. PCB多层板设计总结
  13. vscode 突然无法切换输入法(切换中文输入法)
  14. 西方占星术中的人体十二宫
  15. 【爬虫进阶】常见的反爬手段和解决方法(建议收藏)
  16. 【网页制作】CSS基本选择器讲解(附讲解视频)
  17. 什么是bug?如何描述一个bug?
  18. 【推荐】Windows 服务器必备十大软件
  19. Http——HttpURLConnection详解
  20. docker 安装 rabbitmq详细与遇到错误解决

热门文章

  1. 不要和一种编程语言厮守终生:为工作正确选择(转)
  2. 理解扩散模型:Diffusion Models DDPM
  3. android多语言配置,Android国际化(多语言)实现,支持8.0
  4. 已解决:Window11问题 8080、8081、8082端口占用问题 Port 808X was already in use.
  5. 项目文档之项目可行性研究
  6. Ubuntu20虚拟机克隆以及克隆后静态IP和主机名的修改
  7. 星球专访 | 火币七爷:Prime 阶梯限价购买,前期不会暴涨
  8. 技术人必须掌握素质——深度思考
  9. Uniapp之使用h5+打开地图导航
  10. 大批量的几何图形求交算法