0
votes

Can someone please help me to debug this code? Thanks!

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn import linear_model
data = pd.read_csv('Mower.csv')
data = data.values
y = data[:,2]
x = data[:,:2]
y_train = y[:int(0.3*len(y))]
x_train = x[:int(0.3*len(y)),:]
y_validate = y[int(0.3*len((y))):]
x_validate = x[int(0.3*len((y))):,:]
clf = linear_model.LogisticRegression
clf.fit(x_train,y_train)
y_hat = clf.predict(x_validate)

Gives me following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-77-a0a54feba3ef> in <module>()
      1 clf = linear_model.LogisticRegression
----> 2 clf.fit(x_train,y_train)
      3 y_hat = clf.predict(x_validate)

TypeError: unbound method fit() must be called with LogisticRegression instance as first argument (got ndarray instance instead)
1

1 Answers

5
votes

Instead of

clf = linear_model.LogisticRegression

you want

clf = linear_model.LogisticRegression()

In the first case, clf is set equal to the class linear_model.LogisticRegression, but in the second case it is set equal to an instance of the class linear_model.LogisticRegression.

When you call clf.fit(...) it is expecting an instance of the class linear_model.LogisticRegression as the first argument. If clf is a class, then it is not passed automatically into the first argument, so the fit method finds x_train instead, an instance of the class ndarray. It then complains, because it was expecting an instance of the class linear_model.LogisticRegression instead.

That's what this

unbound method fit() must be called with LogisticRegression instance as first argument (got ndarray instance instead)

is trying to say.