现在先写一个测试libsvm的简单程序,程序参考了libsvm自带的svm-toy。现在要解决的问题是一个二类分类问题。样本总共有120个,每个样本只有两个特征。首先划分好训练集与测试集。训练集取用其中的80个(正、负样本各40),余下的则作为测试集。数据分别存入train.txt和test.txt中。
#include <stdio.h>
#include <ctype.h>
#include <list>
#include "svm.h" //包涵本目录下的SVM.H头文件
#include <fstream>
#include "iostream.h"
using std::ifstream;
void main()
{
/*
struct svm_problem
{
int l;
double *y;
struct svm_node **x;
};
struct svm_node
{
int index;
double value;
};
*/
ifstream inFile;
ifstream inFile1;
svm_problem prob; //建立SVM数据
prob.l=80; //80个样本,前40个为正样本,
double d[40];
int probfeature=2; //样本特征维数
prob.y=new double[prob.l];
svm_parameter param;
//svm参数设置
param.svm_type = C_SVC;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = 0.0001;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 10;
param.eps = 1e-5;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
//分类
if(param.gamma == 0) param.gamma = 0.5; //gamma for poly/rbf/sigmoid
svm_node *x_space = new svm_node[(probfeature+1) * prob.l]; //样本特征存储空间
prob.x = new svm_node *[prob.l]; //没一个X指向一个样本
//数据填充开始
inFile.open("train.txt"); //打开训练数据文件
for(int i=0;i<prob.l;i++)
{
/**/
float fvalue;
for (int j=0;j<probfeature;j++)
{
inFile>>fvalue;
if(fvalue!=0.0)
{
x_space[(probfeature+1)*i+j].index=j+1;
x_space[(probfeature+1)*i+j].value=fvalue;
}
}
x_space[(probfeature+1)*i+probfeature].index=-1;
prob.x[i]=&x_space[(probfeature+1)*i];
if (i<40) //类别标签
prob.y[i]=1;
else
prob.y[i]=-1;
}
inFile.close(); //关闭文件
//数据填充结束
// build model & classify
svm_model *model = svm_train(&prob, ¶m); //开始训练
int test_num=40;
inFile1.open("test.txt");
svm_node x[3]; //定义一个测试样本
for(int i1=0;i1<test_num;i1++)
{
float fvalue;
for (int j=0;j<2;j++)
{
inFile1>>fvalue;
if(fvalue!=0.0)
{
x[j].index=j+1;
x[j].value=fvalue;
}
}
x[2].index=-1;
d[i1]=svm_predict(model,x);
}
inFile1.close();
svm_destroy_model(model);
delete[] x_space;
delete[] prob.x;
delete[] prob.y;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fangfxy/archive/2008/03/17/2191274.aspx