BrianC
BrianC

Reputation: 29

why am I getting AttributeError: 'LinearRegressionGD' object has no attribute 'n_iter'

I'm setting up a linearregression model on my data set but I am encountering an attribute error which I'm having an issue resolving.

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)

I then expected t be able plot the results to see if the linear regresion had converged but I am getting the following error:

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'

Upvotes: 1

Views: 761

Answers (1)

Ali Tou
Ali Tou

Reputation: 2195

You have to write constructor name using 2 underscores before and 2 underscores after init: __init__()

That _init_() function you wrote doesn't run when you create the object, so the object doesn't get any variable named n_iter to use with.

Upvotes: 1

Related Questions