Search code examples
pythonscikit-learnknn

KNeighborsClassifier error: Unknown label type: 'unknown'


I am trying to do KNN using KNeighborsClassifier with following code -

X_train, X_test, y_train, y_test = train_test_split(X_bow, y, test_size=0.30, random_state=42)

neigh = KNeighborsClassifier(n_neighbors=3)
neigh.fit(X_train, y_train)

But I get following error

ValueError: Unknown label type: 'unknown'

X_train is of type scipy.sparse.csr.csr_matrix and y_train is of type numpy.ndarray.

This is the detailed error I get. Why do I get this error?

ValueError                                Traceback (most recent call last)
<ipython-input-278-97b47c930597> in <module>
     10 
     11 neigh = KNeighborsClassifier(n_neighbors=3)
---> 12 neigh.fit(X_train, y_train)

c:\users\kishore\appdata\local\programs\python\python36\lib\site-packages\sklearn\neighbors\base.py in fit(self, X, y)
    903             self.outputs_2d_ = True
    904 
--> 905         check_classification_targets(y)
    906         self.classes_ = []
    907         self._y = np.empty(y.shape, dtype=np.int)

c:\users\kishore\appdata\local\programs\python\python36\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    169     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    170                       'multilabel-indicator', 'multilabel-sequences']:
--> 171         raise ValueError("Unknown label type: %r" % y_type)
    172 
    173 

ValueError: Unknown label type: 'unknown'

Edit 1:

My Y is - array([0, 1, 0, ..., 1, 1, 1], dtype=object)

My X is <5600x6031 sparse matrix of type '' with 586188 stored elements in Compressed Sparse Row format>


Solution

  • So, the problem is that your y is of type object and sklearn cannot recognize that.

    You can use y=y.astype('int') before you pass the variable into the classifier