ryand
ryand

Reputation: 131

In sklearn.KNeighborsClassifier, I got error: Found array with dim 4. Estimator expected <= 2

I have a problem with the program I created to classify images. I store my image in an array

arr = np.concatenate((X1, Y1))

where has size : (80, 128, 128, 3) and i have another one :

arr2 = np.concatenate((X2, Y2))

where has size : (20, 128, 128, 3) I will make array into training data. and create target :

a= np.full((1, 40), 1)
b= np.full((1, 40), 2)
arr3 = np.concatenate((a, b))

and set into knn algorithm

knn=KNeighborsClassifier(n_neighbors=3) #define K=3
knn.fit(arr,arr3)
res = knn.predict(arr2)
print(res)

I don't get results and there is an error: Found array with dim 4. Estimator expected <= 2.

I've also tried to reshape arr and arr2 :

arr5 = arr.reshape(-1,1)
arr6 = arr2.reshape(-1,1)

but also getting errors: Found input variables with inconsistent numbers of samples

I need your opinion about this to fix the problem.

Upvotes: 1

Views: 321

Answers (1)

I&#39;mahdi
I&#39;mahdi

Reputation: 24049

You can read here, For using sklearn.neighbors.KNeighborsClassifier and .fit(X,y) should have shape like :

fit(X, y): Fit the k-nearest neighbors classifier from the training dataset.

Parameters : X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’ Training data. y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) Target values.

For this reason, you need to reshape arr or x_train like (80, 128*128*3) and arr2 or x_test like (20, 128*128*3) and y or arr3 like (80):

(for this reshaping we can use `numpy.reshape(-1) like below.)

from sklearn.neighbors import KNeighborsClassifier
import numpy as np

arr  = np.random.rand(80,128,128,3)
arr2 = np.random.rand(20,128,128,3)

a= np.full((1, 40), 1)
b= np.full((1, 40), 2)
arr3 = np.concatenate((a, b))

knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(arr.reshape(80,-1), arr3.reshape(-1))

res = knn.predict(arr2.reshape(20,-1))
print(res)

Output:

[2 1 1 2 2 1 1 1 2 1 2 1 1 2 2 2 2 1 1 1]

Upvotes: 3

Related Questions