簡體   English   中英

AttributeError: LinearRegression object 沒有屬性 'coef_'

[英]AttributeError: LinearRegression object has no attribute 'coef_'

我一直在嘗試按照 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()

完成所有這些設置后,我運行了以下命令,它返回了正確的 output:

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_'

coef_屬性是在調用fit()方法時創建的。 在此之前,它將是未定義的:

>>> 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()

我在處理線性回歸時也遇到了同樣的問題問題 object 沒有屬性“coef”。 只有語法上有輕微的變化。


linreg = LinearRegression()

linreg.fit(X,y) # fit the linesr model to the data

print(linreg.intercept_)

print(linreg.coef_)

我希望這會幫助你謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM