Python scikit-learn SVM 分类器“ValueError: Found array with dim 3. Expected <= 2”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33162871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:54:51  来源:igfitidea点击:

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

pythonscikit-learnsvm

提问by Hitanshu Tiwari

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

我正在尝试在 MNIST 数据集上实现 SVM 分类器。由于我的参数是 3 维的,因此会引发以下错误:

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?

sklearn 是否支持多维分类器?

采纳答案by Ryan

The problem is with your input data.

问题在于您的输入数据。

You can use sklearnto load a digit dataset as well:

您也可以使用sklearn加载数字数据集:

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

回答by Zahra

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.

假设您的训练数据由 10 张图像组成,每张图像都表示为一个 3x3 矩阵,因此您的输入数据是 3 维的。

[ [[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.

我们可以将每个图像转换为 9 个元素的数组,以便将数据集转换为二维。

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