1. 程式人生 > >Python 普通最小二乘法(OLS)進行多項式擬合

Python 普通最小二乘法(OLS)進行多項式擬合

zlabel predict ylabel model for font 結果 param col

多元函數擬合。如 電視機和收音機價格多銷售額的影響,此時自變量有兩個。

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()

技術分享圖片

擬合的各項評估結果和參數都打印出來了,其中結果函數為:

f(sales) = β0

+ β1*[TV] + β2*[radio]

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

技術分享圖片

圖中,sales 方向上,藍色點為原 sales 實際值,紅色點為擬合函數計算出來的值。其實誤差並不大,部分數據如下。

技術分享圖片

同樣可擬合一元函數;

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)進行多項式擬合