如何为 openCV SVM 格式化数据
Posted
技术标签:
【中文标题】如何为 openCV SVM 格式化数据【英文标题】:How to format data for openCV SVM 【发布时间】:2018-05-05 13:57:24 【问题描述】:我正在尝试训练 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
我的问题是数据的格式吗?我该如何解决?
【问题讨论】:
【参考方案1】:当您没有将火车数据的 dtype 提及为浮点数时,我遇到了类似的问题。这是我运行代码时遇到的错误
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)
【讨论】:
谢谢!我不得不使用 svm.train(np.array(trainingData, np.float32), cv2.ml.ROW_SAMPLE, np.array(labels, np.int32)) 行,但如果没有你的回答就不会发现!以上是关于如何为 openCV SVM 格式化数据的主要内容,如果未能解决你的问题,请参考以下文章