多元函数拟合。如 电视机和收音机价格多销售额的影响,此时自变量有两个。
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()