Python 普通最小二乘法(OLS)進(jìn)行多項(xiàng)式擬合的方法
多元函數(shù)擬合。如 電視機(jī)和收音機(jī)價(jià)格多銷售額的影響,此時(shí)自變量有兩個(gè)。
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()
擬合的各項(xiàng)評(píng)估結(jié)果和參數(shù)都打印出來了,其中結(jié)果函數(shù)為:
f(sales) = β0 + β1*[TV] + β2*[radio]
f(sales) = 2.9211 + 0.0458 * [TV] + 0.188 * [radio]
圖中,sales 方向上,藍(lán)色點(diǎn)為原 sales 實(shí)際值,紅色點(diǎn)為擬合函數(shù)計(jì)算出來的值。其實(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:(嶺回歸交叉驗(yàn)證)
嶺回歸(ridge regression, Tikhonov regularization)是一種專用于共線性數(shù)據(jù)分析的有偏估計(jì)回歸方法,實(shí)質(zhì)上是一種改良的最小二乘估計(jì)法,通過放棄最小二乘法的無偏性,以損失部分信息、降低精度為代價(jià)獲得回歸系數(shù)更為符合實(shí)際、更可靠的回歸方法,對(duì)病態(tài)數(shù)據(jù)的擬合要強(qiáng)于最小二乘法。通常嶺回歸方程的R平方值會(huì)稍低于普通回歸分析,但回歸系數(shù)的顯著性往往明顯高于普通回歸,在存在共線性問題和病態(tài)數(shù)據(jù)偏多的研究中有較大的實(shí)用價(jià)值。
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)行多項(xiàng)式擬合的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中實(shí)現(xiàn)ipaddress網(wǎng)絡(luò)地址的處理
ipaddress庫提供了處理IPv4與IPv6網(wǎng)絡(luò)地址的類。這些類支持驗(yàn)證,查找網(wǎng)絡(luò)上的地址和主機(jī),以及其他常見的操作,本文就來介紹一下這些方法的使用,感興趣的一起來了解一下2021-06-06Python使用Qt5實(shí)現(xiàn)水平導(dǎo)航欄的示例代碼
本文主要介紹了Python使用Qt5實(shí)現(xiàn)水平導(dǎo)航欄的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(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詳解pycharm自動(dòng)import所需的庫的操作方法
這篇文章主要介紹了pycharm自動(dòng)import所需的庫的操作方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11