// test_max.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <cv.h> #include <highgui.h> #include <ml.h> #include <cxcore.h> #include <iostream> using namespace std; int main() { // step 1: //训练数据的分类标记,即4类 float labels[16] = {1.0, 1.0,1.0,1.0,2.0,2.0,2.0,2.0,3.0,3.0,3.0,3.0,4.0,4.0,4.0,4.0}; CvMat labelsMat = cvMat(16, 1, CV_32FC1, labels); //训练数据矩阵 float trainingData[16][2] = { {0, 0}, {4, 1}, {4, 5}, {-1, 6},{3,11},{-2,10},{4,30},{0,25},{10,13},{15,12},{25,40},{11,35},{8,1},{9,6},{15,5},{20,-1} }; CvMat trainingDataMat = cvMat(16, 2, CV_32FC1, trainingData); // step 2: //训练参数设定 CvSVMParams params; params.svm_type = CvSVM::C_SVC; //SVM类型 params.kernel_type = CvSVM::LINEAR; //核函数的类型 //SVM训练过程的终止条件, max_iter:最大迭代次数 epsilon:结果的精确性 params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, FLT_EPSILON ); // step 3: //启动训练过程 CvSVM SVM; SVM.train( &trainingDataMat, &labelsMat, NULL,NULL, params); // step 4: //使用训练所得模型对新样本进行分类测试 for (int i=-5; i<15; i++) { for (int j=-5; j<15; j++) { float a[] = {i,j}; CvMat sampleMat; cvInitMatHeader(&sampleMat,1,2,CV_32FC1,a); cvmSet(&sampleMat,0,0,i); // Set M(i,j) cvmSet(&sampleMat,0,1,j); // Set M(i,j) float response = SVM.predict(&sampleMat); cout<<response<<" "; } cout<<endl; } // step 5: //获取支持向量 int c = SVM.get_support_vector_count(); cout<<endl; for (int i=0; i<c; i++) { const float* v = SVM.get_support_vector(i); cout<<*v<<" "; } cout<<endl; system("pause"); return 0; }
原文地址:http://blog.csdn.net/hxysea/article/details/26224523