Python 普通最小二乘法(OLS)进行多项式拟合的方法

yipeiwu_com5年前Python基础

多元函数拟合。如 电视机和收音机价格多销售额的影响,此时自变量有两个。

python 解法:

import numpy as np
import pandas as pd
#import statsmodels.api as sm #方法一
import statsmodels.formula.api as smf #方法二
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
 
df = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
X = df[['TV', 'radio']]
y = df['sales']
 
#est = sm.OLS(y, sm.add_constant(X)).fit() #方法一
est = smf.ols(formula='sales ~ TV + radio', data=df).fit() #方法二
y_pred = est.predict(X)
 
df['sales_pred'] = y_pred
print(df)
print(est.summary()) #回归结果
print(est.params) #系数
 
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') #ax = Axes3D(fig)
ax.scatter(X['TV'], X['radio'], y, c='b', marker='o')
ax.scatter(X['TV'], X['radio'], y_pred, c='r', marker='+')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

Python 普通最小二乘法(OLS)进行多项式拟合

拟合的各项评估结果和参数都打印出来了,其中结果函数为:

f(sales) = β0 + β1*[TV] + β2*[radio]

f(sales) = 2.9211 + 0.0458 * [TV] + 0.188 * [radio]

Python 普通最小二乘法(OLS)进行多项式拟合

图中,sales 方向上,蓝色点为原 sales 实际值,红色点为拟合函数计算出来的值。其实误差并不大,部分数据如下。

Python 普通最小二乘法(OLS)进行多项式拟合

同样可拟合一元函数;

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
 
df = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
X = df['TV']
y = df['sales']
 
est = smf.ols(formula='sales ~ TV ', data=df).fit()
y_pred = est.predict(X)
print(est.summary())
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(X, y, c='b')
ax.plot(X, y_pred, c='r')
plt.show()

Python 普通最小二乘法(OLS)进行多项式拟合

Python 普通最小二乘法(OLS)进行多项式拟合

Ridge Regression:(岭回归交叉验证)

岭回归(ridge regression, Tikhonov regularization)是一种专用于共线性数据分析的有偏估计回归方法,实质上是一种改良的最小二乘估计法,通过放弃最小二乘法的无偏性,以损失部分信息、降低精度为代价获得回归系数更为符合实际、更可靠的回归方法,对病态数据的拟合要强于最小二乘法。通常岭回归方程的R平方值会稍低于普通回归分析,但回归系数的显著性往往明显高于普通回归,在存在共线性问题和病态数据偏多的研究中有较大的实用价值。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
from mpl_toolkits.mplot3d import Axes3D
 
df = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
X = np.asarray(df[['TV', 'radio']])
y = np.asarray(df['sales'])
 
clf = linear_model.RidgeCV(alphas=[i+1 for i in np.arange(200.0)]).fit(X, y)
y_pred = clf.predict(X)
df['sales_pred'] = y_pred
print(df)
print("alpha=%s, 常数=%.2f, 系数=%s" % (clf.alpha_ ,clf.intercept_,clf.coef_))
 
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(df['TV'], df['radio'], y, c='b', marker='o')
ax.scatter(df['TV'], df['radio'], y_pred, c='r', marker='+')
ax.set_xlabel('TV')
ax.set_ylabel('radio')
ax.set_zlabel('sales')
plt.show()

输出结果:alpha=150.0, 常数=2.94, 系数=[ 0.04575621 0.18735312]

以上这篇Python 普通最小二乘法(OLS)进行多项式拟合的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现微信跳一跳辅助工具步骤详解

说明 1.windows上安装安卓模拟器,安卓版本5.1以上 2.模拟器里下载安装最新的微信6.6.1 3.最好使用python2.7,python3的pyhook包有bug,解决比较麻...

python实现内存监控系统

python实现内存监控系统

本文实例为大家分享了python实现内存监控系统的具体代码,供大家参考,具体内容如下 思路:通过系统命令或操作系统文件获取到内存信息(linux 内存信息存在/proc/meminfo...

实例讲解Python的函数闭包使用中应注意的问题

昨天正当我用十成一阳指功力戳键盘、昏天暗地coding的时候,正好被人问了一个问题,差点没收好功,洪荒之力侧漏震伤桌边的人,废话不多说,先上栗子(精简版,只为说明问题): from...

python实现机械分词之逆向最大匹配算法代码示例

python实现机械分词之逆向最大匹配算法代码示例

逆向最大匹配方法 有正即有负,正向最大匹配算法大家可以参阅/post/127404.htm 逆向最大匹配分词是中文分词基本算法之一,因为是机械切分,所以它也有分词速度快的优点,且逆向最大...

Python中使用logging模块代替print(logging简明指南)

替换print?print怎么了? print 可能是所有学习Python语言的人第一个接触的东西。它最主要的功能就是往控制台 打印一段信息,像这样: 复制代码 代码如下: print...