属性错误:线性回归对象没有属性'model'



我在sklearn中看到了多个关于以下错误的类似问题:

属性错误:LinearRegression对象没有属性…'

我找不到任何关于我的问题的提示:

AttributeError: LinearRegression object has no attribute 'model'

我试着用下面的代码做一个多元线性回归y~x:

import statsmodels.api as sma
from sklearn import linear_model
#https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html
#perform linear regression
df_x = df.drop('Migration distance',1) #for simplicity I did't use any testing data just this 2
df_y = df['Migration distance']
reg = linear_model.LinearRegression().fit(df_x, df_y)
reg_score=reg.score(df_x, df_y)
print('R2 score:',reg_score)
#plot the residuals
fig = plt.figure(figsize=(12,8))
fig = sma.graphics.plot_regress_exog(reg, 'Migration distance', fig=fig)

但每当我试图绘制残差时,就会出现这种错误:

AttributeError                            Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_12904/573591118.py in <module>
10 
11 fig = plt.figure(figsize=(12,8))
---> 12 fig = sma.graphics.plot_regress_exog(reg, 'Migration distance', fig=fig)
C:ProgramDataAnaconda3libsite-packagesstatsmodelsgraphicsregressionplots.py in plot_regress_exog(results, exog_idx, fig)
218     fig = utils.create_mpl_fig(fig)
219 
--> 220     exog_name, exog_idx = utils.maybe_name_or_idx(exog_idx, results.model)
221     results = maybe_unwrap_results(results)
222 
AttributeError: 'LinearRegression' object has no attribute 'model'

我认为我的线性回归是有效的,因为我可以计算R2分数,但我不知道如何克服这个误差来绘制残差。

正如graphics.plot_regress_exog的文档所暗示的,results参数中传递的模型(即此处的reg(必须是

以resid、model.endog和model.exog为属性的结果实例。

统计模型模型,而不是scikit学习模型,如您的LinearRegression。换句话说,该功能不能与scikit学习模型一起使用。

由于您实际上是在做一个简单的OLS回归,如果您真的需要该功能,我建议使用相应的统计模型,而不是scikit学习模型。

最新更新