我正在尝试培训openCV的SVM,在阅读完文档并在线查看示例后,我认为问题在于我的训练数据和/或标签是如何格式化的,但我不确定如何修复它。
这是我的代码:
def train_svm(trainingData,labels):
svm_params = dict( kernel_type = cv2.ml.SVM_LINEAR, svm_type = cv2.ml.SVM_C_SVC, C=2.67, gamma=3)
svm = cv2.ml.SVM_create()
svm.train(np.array(trainingData),np.array(labels),params=svm_params)
svm.save('svm_data.dat')
这就是trainingData的样子:
[[5795, 41957, 65, 11910, 23, 11470, 4928, 652, 53.1, 43.0, 30.9, 1401, 40311], [9894, 47158, 90, 6525, 36, 7179, 5239, 679, 53.1, 55.0, 37.0, 1358, 110809], [8739, 37084, 0, 2586, 0, 16315, 11579, 497, 77.0, 21.0, 34.0, 1358, 90314], [12249, 50962, 0, 362, 60, 12555, 114, 498, 82.0, 27.0, 54.0, 1359, 91902], [15187, 43766, 139, 2145, 91, 10767, 4026, 679, 82.0, 31.0, 48.9, 1359, 91509], [115, 40564, 125, 371, 812, 31401, 2059, 1353, 37.9, 65.0, 27.0, 1356, 20999], [75, 202, 2, 371, 4, 70454, 5046, 646, 39.9, 89.0, 37.0, 1357, 110909], [0, 0, 0, 0, 0, 62941, 13209, 650, 45.5, 80.0, 37.7, 1333, 111517], [0, 0, 0, 0, 0, 62593, 13690, 517, 46.4, 91.0, 43.9, 1126, 111017], [0, 42, 0, 268, 0, 60787, 15286, 417, 50.0, 57.0, 35.1, 1552, 110717], [8457, 28320, 56, 815, 413, 37816, 454, 469, 78.1, 46.0, 55.9, 1359, 82502], [8797, 28189, 21, 721, 349, 37940, 313, 470, 80.1, 40.0, 54.0, 1358, 83017], [1063, 135, 17, 5947, 752, 67682, 744, 460, 82.9, 24.0, 42.1, 1562, 81802], [7906, 39942, 109, 926, 196, 26724, 534, 463, 84.9, 26.0, 46.0, 1359, 82302], [8834, 50751, 67, 722, 119, 15431, 402, 474, 84.9, 29.0, 48.9, 1359, 82402], [4493, 16618, 23, 4159, 0, 41145, 9916, 446, 91.9, 23.0, 48.9, 1358, 81512], [6309, 34053, 13, 5698, 0, 20845, 9415, 467, 98.1, 23.0, 54.0, 1358, 81612]]
这就是标签的样子:
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
我不断收到此错误消息:
svm.train(np.array(trainingData),np.array(labels),params=svm_params)
TypeError: only length-1 arrays can be converted to Python scalars
我的问题是数据格式的方式吗?我该如何解决?
答案 0 :(得分:1)
当你没有提到火车数据的dtype为float时,我遇到了类似的问题。这是我运行代码时遇到的错误
p:857: error: (-5) train data must be floating-point matrix in function cvCheckTrainData
只需替换此行:
svm.train(np.array(trainingData),np.array(labels),params=svm_params)
用这个:
svm.train(np.array(trainingData,np.float32),np.array(labels,np.int32),params=svm_params)