標籤:nump for 多項式擬合 cti 資料 info div summary models
多元函數擬合。如 電視機和收音機價格多銷售額的影響,此時自變數有兩個。
python 解法:
import numpy as npimport pandas as pd#import statsmodels.api as sm #方法一import statsmodels.formula.api as smf #方法二import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Ddf = 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_predprint(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 實際值,紅色點為擬合Function Compute出來的值。其實誤差並不大,部分資料如下。
同樣可擬合一元函數;
import numpy as npimport pandas as pdimport statsmodels.formula.api as smfimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Ddf = 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)進行多項式擬合