首页 > 解决方案 > ValueError:为 SVM.Fit 模型设置带有序列的数组元素

问题描述

我已经使用 sklearn 内置函数classifier.fit(X_svm_train,Y_train)进行二进制分类。

我的X_svm_trainY_train尺寸是一样的,但我很困惑为什么我会收到这个错误以及如何纠正它:

X_svm_train:(200, 7290)
Y_train=200
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
classifier=SVC(gamma=0.01,C=10,kernel='poly')
classifier.fit(X_svm_train,Y_train)
c:\users\user\appdata\local\programs\python\python37\lib\site- 
       packages\sklearn\svm\base.py in fit(self, X, y, sample_weight)
       144         X, y = check_X_y(X, y, dtype=np.float64,
       145                          order='C', accept_sparse='csr',
    --> 146                          accept_large_sparse=False)
       147         y = self._validate_targets(y)
       148 

c:\users\user\appdata\local\programs\python\python37\lib\site- 
packages\sklearn\utils\validation.py in check_X_y(X, y, accept_sparse, 
accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, 
allow_nd, multi_output, ensure_min_samples, ensure_min_features, 
 y_numeric, warn_on_dtype, estimator)
         717                     ensure_min_features=ensure_min_features,
         718                     warn_on_dtype=warn_on_dtype,
     --> 719                     estimator=estimator)
         720     if multi_output:
         721         y = check_array(y, 'csr', force_all_finite=True, 
  ensure_2d=False,

c:\users\user\appdata\local\programs\python\python37\lib\site- 
packages\sklearn\utils\validation.py in check_array(array, accept_sparse, 
accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, 
allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, 
estimator)
    494             try:
    495                 warnings.simplefilter('error', ComplexWarning)
--> 496                 array = np.asarray(array, dtype=dtype, 
  order=order)
    497             except ComplexWarning:
    498                 raise ValueError("Complex data not supported\n"

c:\users\user\appdata\local\programs\python\python37\lib\site- 
packages\numpy\core\numeric.py in asarray(a, dtype, order)
    536 
    537     """
--> 538     return array(a, dtype, copy=False, order=order)
    539 
    540 

ValueError: setting an array element with a sequence.

标签: pythonarraysmachine-learningscikit-learnsvm

解决方案


从 Stacktrace 看,这是由于Y_trainor的形状不正确造成的X_train,请确保您的Y_trainis 的 Shape (Num_rows , 1)

另外,确保X_train有形状(Num_rows , num_features)

AValueError: setting an array element with a sequence通常是由于试图将一系列数字塞入单个数字槽而引起的。

例如->

import numpy

numpy.array([1,2,3])               #good

numpy.array([1, (2,3)])            #Fail, can't convert a tuple into a numpy 
                                   #array element

推荐阅读