python实现多元线性拟合、一元多项式拟合、多元多项式拟合

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

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


误差分析
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_model


filename = "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_model

filename = "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_model

filename = "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_model

filename = "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, x1∗x1, x1∗x2, x1∗x3, x1∗x4, x2∗x2, x2∗x3, x2∗x4, x3∗x3, x3∗x4, x4∗x4]

对应的方程式为: intercept+coefficients∗variableX.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
————————————————
版权声明:本文为CSDN博主「qq_33511693」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_33511693/java/article/details/105169807

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容