为什么我得到AttributeError:'LinearRegressionGD'对象没有属性'n_iter'

时间:2019-05-11 13:19:01

标签: python python-3.x scikit-learn linear-regression attributeerror

我正在数据集上建立线性回归模型,但遇到属性错误,正在解决问题。

class LinearRegressionGD (object):

    def _init_(self, eta=0.001, n_iter=20):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        self.w = np.zeros(1 + X.shape[1])
        self.cost_ = {}

        for i in range(self.n_iter):
            output = self.net_input (X)
            errors = (y - output)
            self.w_[1:] += self.eta * X.T.dot(errors)
            self.w_[0] += self.eta * errors.sum()
            cost = (errors**2).sum() / 2.0
            self.cost_.append(cost)
        return self

    def net_input(self, X):
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        return self.net_input(X)

    X = racing[["BSP"]].values
    y = racing[["Position"]].values
    from sklearn.preprocessing import StandardScaler
    sc_X = StandardScaler()
    sc_y = StandardScaler()
    X_std = sc_X.fit_transform(X)
    y_std = sc_y.fit_transform(y)
    lr = LinearRegressionGD()
    lr.fit(X_std, y_std)

然后我希望无法绘制结果以查看线性递归是否收敛,但是出现以下错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-23-c876c2ee7b9e> in <module>
----> 1 class LinearRegressionGD (object):
      2 
      3     def _init_(self, eta=0.001, n_iter=20):
      4         self.eta = eta
      5         self.n_iter = n_iter

<ipython-input-23-c876c2ee7b9e> in LinearRegressionGD()
     32     y_std = sc_y.fit_transform(y)
     33     lr = LinearRegressionGD()
--->     34     lr.fit(X_std, y_std)

<ipython-input-22-19842f46cb51> in fit(self, X, y)
      9         self.cost_ = {}
     10 
---> 11         for i in range(self.n_iter):
     12             output = self.net_input (X)
     13             errors = (y - output)

AttributeError: 'LinearRegressionGD' object has no attribute 'n_iter'

1 个答案:

答案 0 :(得分:1)

您必须在map之前使用2个下划线,并在init之后使用2个下划线来编写构造函数名称:__init__()

您创建的_init_()函数在创建对象时不会运行,因此该对象不会获得任何名为n_iter的变量。