在使用svm的时候,libsvm无疑是一大利器,有了它,svm的应用简直是手到擒来啊!
那么问题来了,生成libsvm数据格式文件哪家强?
当然使用FormatDatalibsvm.xls这个是so easy了,however在一个程序中如何实现自己调用FormatDatalibsvm.xls来生成文件,我不会啊!
为了把在一个系统中通过特征提取得到目标的特征向量转化成libsvm能使用的格式,就自己动手丰衣足食吧!
下面是这个简单的小程序:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream> //使用istringstream时需要包含该文件
using namespace std;
using std::vector;
int main()
{
struct featureVector{
string label;
vector<string> values;
};
string line, word , buff; //分别保存来自文件的一行和一个单词
string inAdress, outAdress;
cout << "input the infile address"<< endl;
cin >> inAdress;
cout << "input the outfile address" << endl;
cin >> outAdress;
ifstream infile(inAdress);//格式如"D://t.txt"
ofstream outfile(outAdress);//格式如"D://tt.txt"
vector<featureVector> objectPic; //保存来自文件的所有记录
while (getline(infile, line)){
int i = 0;
featureVector info; //创建一个保存记录数据的对象
istringstream record(line); //将记录绑定在刚刚读入的行
record >> info.label; //读取label
while (record >> word) //读取特征向量数据
{
if (i != 0) //每行的第一个为标签,不用序号
{
buff = i + '0'; //values是一个string型的vector,所以要将i转换一下类型
info.values.push_back(buff);
info.values.push_back(":");
info.values.push_back(word); //保持它们
}
i++;
}
objectPic.push_back(info); //将此记录追加到objectPic的末尾
}
for (const auto &entry : objectPic){ //对objectPic中的每一项
int j = 0;
outfile << entry.label;
for (const auto &nums : entry.values) {
if (j%3 == 0) //在每一个向量的值后面才需要加上空格
outfile << " ";
outfile << nums;
j++;
}
outfile << "\n"; //一条记录输出完后换行
}
getchar();
return 0;
}
原始目标提取的数据如:
1 23 44 56 89 33
0 34 55 98 12 78
1 19 40 60 93 35
则得到的数据如:
1 1:44 2:56 3:89 4:33
0 1:55 2:98 3:12 4:78
1 1:40 2:60 3:93 4:35