使用openCV SVM的TypeError:只能将size-1数组转换为Python标量

时间:2018-06-18 12:09:09

标签: python python-2.7 opencv

我收到了TypeError消息,只有size-1数组可以转换为Python标量。我知道标量是预期的,但我想要提供给我的支持向量机的数据不是标量而是矩阵。我需要改变什么?

import cv2
import numpy as np


class StatModel(object):
    '''parent class - starting point to add abstraction'''    
    def load(self, fn):
        self.model.load(fn)
    def save(self, fn):
        self.model.save(fn)


class SVM(StatModel):
    '''wrapper for OpenCV SimpleVectorMachine algorithm'''
    def __init__(self):
        self.model = cv2.ml.SVM_create()

    def train(self, samples, responses):
        #setting algorithm parameters
        params = dict( kernel_type = cv2.ml.SVM_LINEAR, 
                       svm_type = cv2.ml.SVM_C_SVC,
                       C = 1 )
        self.model.train(samples, responses, params = params)

    def predict(self, samples):
        return np.float32( [self.model.predict(s) for s in samples])


samples = np.array(np.random.random((4,2)), dtype = np.float32)
y_train = np.array([1.,0.,0.,1.], dtype = np.float32)

clf = SVM()
clf.train(samples, y_train)
y_val = clf.predict(samples)

完整错误信息是:

Traceback (most recent call last):
  File "test.py", line 33, in <module>
    clf.train(samples, y_train)
  File "test.py", line 23, in train
    self.model.train(samples, responses, params = params)
TypeError: only size-1 arrays can be converted to Python scalars

0 个答案:

没有答案