Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python scikit-learn SVM Classifier "ValueError: Found array with dim 3. Expected <= 2"

I am trying to implement SVM Classifier over MNIST dataset. As my parameters are 3 dimensional its throwing the following error:

ValueError: Found array with dim 3. Expected <= 2

Following is my code snippet:

import mnist
from sklearn import svm

training_images, training_labels = mnist.load_mnist("training", digits = [1,2,3,4])
classifier = svm.SVC()
classifier.fit(training_images, training_labels)

Does sklearn support a multi-dimensional classifier?

like image 854
Hitanshu Tiwari Avatar asked Oct 16 '15 05:10

Hitanshu Tiwari


2 Answers

One option for fixing the problem would be to reshape the input data into a 2-dimensional array.

Let's assume that your training data consists of 10 images which are each represented as an 3x3 matrix and therefore your input data is 3-dimensional.

[ [[1,2,3],   [[1,2,3],           [
   [4,5,6],    [4,5,6],            image 10 
   [7,8,9]] ,  [7,8,9]]  , ... ,           ] ]

We can turn each image into an array of 9 elements in order to convert the dataset into 2-dimensions.

dataset_size = len(training_images)
TwoDim_dataset = dataset.reshape(dataset_size,-1)

This would turn the data into the following shape:

[ [1,2,3,4,5,6,7,8,9]  ,  [1,2,3,4,5,6,7,8,9]  , ... ,  [image 10] ]
like image 178
Zahra Avatar answered Sep 24 '22 23:09

Zahra


The problem is with your input data.

You can use sklearn to load a digit dataset as well:

from sklearn.datasets import load_digits
from sklearn import svm

digits = load_digits()
X = digits.data
y = digits.target

classifier = svm.SVC()
classifier.fit(X[:1000], y[:1000])
predictions = classifier.predict(X[1000:])
like image 42
Ryan Avatar answered Sep 23 '22 23:09

Ryan