使用sklearn SVC(),出现以下错误
import sklearn
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
from sklearn.svm import SVC
# create the model
mySVC = SVC()
# fit the model to data
mySVC.fit(X,y)
# test the model on (new) data
result = mySVC.predict([3, 5, 4, 2])
print(result)
print(iris.target_names[result])
ValueError Traceback (most recent call last)
<ipython-input-47-8994407a09e3> in <module>()
1 # test the model on (new) data
----> 2 result = mySVC.predict([3, 5, 4, 2])
3 print(result)
4 print(iris.target_names[result])
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/svm/base.py in predict(self, X)
546 Class labels for samples in X.
547 """
--> 548 y = super(BaseSVC, self).predict(X)
549 return self.classes_.take(np.asarray(y, dtype=np.intp))
550
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/svm/base.py in predict(self, X)
306 y_pred : array, shape (n_samples,)
307 """
--> 308 X = self._validate_for_predict(X)
309 predict = self._sparse_predict if self._sparse else self._dense_predict
310 return predict(X)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/svm/base.py in _validate_for_predict(self, X)
437 check_is_fitted(self, 'support_')
438
--> 439 X = check_array(X, accept_sparse='csr', dtype=np.float64, order="C")
440 if self._sparse and not sp.isspmatrix(X):
441 X = sp.csr_matrix(X)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/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)
439 "Reshape your data either using array.reshape(-1, 1) if "
440 "your data has a single feature or array.reshape(1, -1) "
--> 441 "if it contains a single sample.".format(array))
442 array = np.atleast_2d(array)
443 # To ensure that array flags are maintained
ValueError: Expected 2D array, got 1D array instead:
array=[3. 5. 4. 2.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
答案 0 :(得分:2)
正如所提到的错误,您将必须传递二维数组。您可以尝试使用以下方法:
result = mySVC.predict([[3, 5, 4, 2]])
您需要传递样本,这里的每个样本都是一个数组,所以您传递的只是一个样本(因为一个样本具有4个特征)而不是样本。请注意,对于按顺序传递给预测的每个样本,您还将收到预测的数组/列表。
预测(X)
对X中的样本进行分类。
对于一类模型,返回+1或-1。
参数:
X:{类似数组,稀疏矩阵},形状(n_samples,n_features) 对于kernel =“ precomputed”,X的预期形状为[n_samples_test, n_samples_train]
返回:
y_pred:数组,形状(n_samples个)
X中样本的类别标签。