AttributeRor:LinearRegression对象没有“coef”属性

2024-05-16 21:14:31 发布

您现在位置:Python中文网/ 问答频道 /正文

根据bigdataexaminer的教程,我一直试图通过线性回归来拟合这些数据。直到现在一切都很好。我从sklearn导入LinearRegression,并将系数的数目打印得很好。这是我试图从控制台获取系数之前的代码。

import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import sklearn
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression

boston = load_boston()
bos = pd.DataFrame(boston.data)
bos.columns = boston.feature_names
bos['PRICE'] = boston.target

X = bos.drop('PRICE', axis = 1)

lm = LinearRegression()

在完成所有这些设置之后,我运行以下命令,它返回正确的输出:

In [68]: print('Number of coefficients:', len(lm.coef_)

Number of coefficients: 13

但是,现在如果我再次尝试打印同一行,或者使用“lm.coef”,它会告诉我coef不是LinearRegression的属性,就在我成功使用它之后,在我再次尝试之前,我没有接触任何代码。

In [70]: print('Number of coefficients:', len(lm.coef_))

Traceback (most recent call last):

 File "<ipython-input-70-5ad192630df3>", line 1, in <module>
print('Number of coefficients:', len(lm.coef_))

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

Tags: of代码importnumberlenassklearnboston
1条回答
网友
1楼 · 发布于 2024-05-16 21:14:31

当调用fit()方法时,将创建coef_属性。在此之前,它将是未定义的:

>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.datasets import load_boston
>>> from sklearn.linear_model import LinearRegression

>>> boston = load_boston()

>>> lm = LinearRegression()
>>> lm.coef_
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-975676802622> in <module>()
      7 
      8 lm = LinearRegression()
----> 9 lm.coef_

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

如果我们调用fit(),将定义系数:

>>> lm.fit(boston.data, boston.target)
>>> lm.coef_
array([ -1.07170557e-01,   4.63952195e-02,   2.08602395e-02,
         2.68856140e+00,  -1.77957587e+01,   3.80475246e+00,
         7.51061703e-04,  -1.47575880e+00,   3.05655038e-01,
        -1.23293463e-02,  -9.53463555e-01,   9.39251272e-03,
        -5.25466633e-01])

我的猜测是,当你运行有问题的线路时,不知怎么的,你忘记给fit()打电话了。

相关问题 更多 >