AttributeError: LinearRegression object has no attribute 'model'

AttributeError: LinearRegression object has no attribute 'model'

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

'AttributeError: LinearRegression object has no attribute...'

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

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)
~\AppData\Local\Temp/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:\ProgramData\Anaconda3\lib\site-packages\statsmodels\graphics\regressionplots.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_exogdocumentation 暗示的那样,在 results 参数中传递的模型(即这里的 reg)必须是

A result instance with resid, model.endog and model.exog as attributes.

即一个 statsmodels 模型,而不是一个 scikit-learn 模型,就像你的 LinearRegression 一样。换句话说,该函数不能用于 scikit-learn 模型。

由于您实际上是在进行简单的 OLS 回归,如果您确实需要该功能,我建议您使用相应的 statsmodels 模型而不是 scikit-learn 模型。