Setting an array element with a sequence error while training SVM to classify images

狂风中的少年 提交于 2019-12-11 05:58:24

问题


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)

Now for this I'm getting the error:

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

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!


回答1:


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)


来源:https://stackoverflow.com/questions/40514019/setting-an-array-element-with-a-sequence-error-while-training-svm-to-classify-im

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!