Python AttributeError:LinearRegression对象没有属性';coef';
我一直在尝试通过线性回归拟合这些数据,遵循BigDataChecker的教程。到目前为止,一切都很顺利。我从sklearn中导入了线性回归,并很好地打印了系数的数量。这是我试图从控制台获取系数之前的代码Python AttributeError:LinearRegression对象没有属性';coef';,python,python-3.x,scikit-learn,linear-regression,attributeerror,Python,Python 3.x,Scikit Learn,Linear Regression,Attributeerror,我一直在尝试通过线性回归拟合这些数据,遵循BigDataChecker的教程。到目前为止,一切都很顺利。我从sklearn中导入了线性回归,并很好地打印了系数的数量。这是我试图从控制台获取系数之前的代码 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_
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_uu',它告诉我coef_u不是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_'
[70]中的:print('系数数:',len(lm.coef)))
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
打印('系数的数量:',len(lm.coef_))
AttributeError:“LinearRegression”对象没有属性“coef\ux”
当调用fit()
方法时,将创建coef\uuu
属性。在此之前,它将是未定义的:
>>> 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()
。在哪里调用fit方法?只有您共享的部分,len(lm.coef_)无法打印13。我从未调用fit方法,但我可以向您保证,第一次运行该行时,它肯定返回了13。我不确定这是否是python 3的问题或其他问题,但它第一次确实打印了它。@destoxia如果你不适合这个函数,怎么会有一个系数???@destoxia本质上你是在试图解决y=mx+c中的m,m是你的系数。68到70之间有什么?我猜类似于runfile(…)
?谢谢你,这似乎解决了问题,尽管我不确定它第一次没有安装时是如何工作的。
>>> 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])