在训练SVM对图像进行分类时将序列元素设置为序列错误 [英] Setting an array element with a sequence error while training SVM to classify images
问题描述
我正在尝试在python中使用SVM在具有1022个图像和1022个多类标签的图像中进行图像分类(每个标签有14个类)。
I'm trying to do image classification using SVM in python with 1022 images and 1022 multi-class labels (each label has 14 classes).
mypath = 'path'
k = listdir(mypath)
images = np.empty((len(k)-1), dtype=object)
resized_imgs = np.empty((len(k)-1),dtype=object)
for n in range(0, len(k)-1):
images[n] = cv2.imread(join(mypath,k[n]),0) #Reading images in grayscale
resized_imgs[n] = cv2.resize(images[n],(32,32)) #Resizing images
for i in range(0,len(k)-1):
a=resized_imgs[i].mean()
b=resized_imgs[i].std()
t=np.ndarray([32,32])
t.fill(1)
t=t*a
resized_imgs[i]=(resized_imgs[i]-a)/b
X_train = resized_imgs
for i in range(len(k)-1):
X_train[i] = X_train[i].flatten().tolist()
y_train = np.array(y_train)
for i in range(len(k)-1):
y_train[i] = y_train[i].flatten().tolist()
clf=svm.SVC(gamma=0.001)
clf.fit(X_train,y_train)
现在,我遇到了错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-469-bfab446776df> in <module>()
----> 1 clf.fit(X_train,y_train[:,0])
C:\Users\user\Anaconda3\lib\site-packages\sklearn\svm\base.py in fit(self, X, y, sample_weight)
148 self._sparse = sparse and not callable(self.kernel)
149
--> 150 X = check_array(X, accept_sparse='csr', dtype=np.float64, order='C')
151 y = self._validate_targets(y)
152
C:\Users\user\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
371 force_all_finite)
372 else:
--> 373 array = np.array(array, dtype=dtype, order=order, copy=copy)
374
375 if ensure_2d:
ValueError: setting an array element with a sequence.
我不知道这是由于X_train数组大小不匹配造成的,因为每个元素X_train的列表是1024个归一化像素值的列表,而y_train的每个元素都对应于14个属性的列表。
I don't see how this could be due to mismatch of sizes of array of X_train because each element of X_train is a list of 1024 normalized pixel values and each element of y_train corresponds to a list of 14 attributes.
可以提供任何帮助。谢谢!
Any help would be appreciated. Thanks!
推荐答案
我知道我要去哪里了。事实证明,X_train的dtype是对象类型,因此我不得不将其更改为float。
I figured where I was going wrong. Turns out, the dtype for X_train was object type so I had to change it to float.
使用以下代码进行相同的操作,
Used the following code for the same,
np.array(list(X_train), dtype=np.float)
这篇关于在训练SVM对图像进行分类时将序列元素设置为序列错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!