2016-03-04 52 views
0

有人可以幫我調試這段代碼嗎?謝謝!使用SciKit的Logisitc迴歸瞭解

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) 

給了我以下錯誤:

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

回答

5

而不是

clf = linear_model.LogisticRegression 

你想

clf = linear_model.LogisticRegression() 

在第一種情況下,clf設置等於類別linear_model.LogisticRegression,但在第二種情況下,它被設置爲等於實例類別linear_model.LogisticRegression

當您致電clf.fit(...)時,它期望第linear_model.LogisticRegression類的實例作爲第一個參數。如果clf是一個類,那麼它不會自動傳遞到第一個參數中,因此fit方法會找到x_train而不是ndarray類的一個實例。然後它會抱怨,因爲它期望的是類linear_model.LogisticRegression的一個實例。

這就是這個

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

想說。