Python 普通最小二乘法(OLS)進(jìn)行多項式擬合的方法
多元函數(shù)擬合。如 電視機(jī)和收音機(jī)價格多銷售額的影響,此時自變量有兩個。
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()) #回歸結(jié)果
print(est.params) #系數(shù)
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()

擬合的各項評估結(jié)果和參數(shù)都打印出來了,其中結(jié)果函數(shù)為:
f(sales) = β0 + β1*[TV] + β2*[radio]
f(sales) = 2.9211 + 0.0458 * [TV] + 0.188 * [radio]

圖中,sales 方向上,藍(lán)色點為原 sales 實際值,紅色點為擬合函數(shù)計算出來的值。其實誤差并不大,部分?jǐn)?shù)據(jù)如下。

同樣可擬合一元函數(shù);
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()


Ridge Regression:(嶺回歸交叉驗證)
嶺回歸(ridge regression, Tikhonov regularization)是一種專用于共線性數(shù)據(jù)分析的有偏估計回歸方法,實質(zhì)上是一種改良的最小二乘估計法,通過放棄最小二乘法的無偏性,以損失部分信息、降低精度為代價獲得回歸系數(shù)更為符合實際、更可靠的回歸方法,對病態(tài)數(shù)據(jù)的擬合要強于最小二乘法。通常嶺回歸方程的R平方值會稍低于普通回歸分析,但回歸系數(shù)的顯著性往往明顯高于普通回歸,在存在共線性問題和病態(tài)數(shù)據(jù)偏多的研究中有較大的實用價值。
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, 常數(shù)=%.2f, 系數(shù)=%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()
輸出結(jié)果:alpha=150.0, 常數(shù)=2.94, 系數(shù)=[ 0.04575621 0.18735312]
以上這篇Python 普通最小二乘法(OLS)進(jìn)行多項式擬合的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中實現(xiàn)ipaddress網(wǎng)絡(luò)地址的處理
ipaddress庫提供了處理IPv4與IPv6網(wǎng)絡(luò)地址的類。這些類支持驗證,查找網(wǎng)絡(luò)上的地址和主機(jī),以及其他常見的操作,本文就來介紹一下這些方法的使用,感興趣的一起來了解一下2021-06-06
Python使用Qt5實現(xiàn)水平導(dǎo)航欄的示例代碼
本文主要介紹了Python使用Qt5實現(xiàn)水平導(dǎo)航欄的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
關(guān)于python基礎(chǔ)數(shù)據(jù)類型bytes進(jìn)制轉(zhuǎn)換
Python 3.x之后,Python自帶字符默認(rèn)使用utf-8格式編碼和顯示,bytes數(shù)據(jù)類型是utf-8格式的二進(jìn)制形式的不可變序列,需要的朋友可以參考下2023-05-05

