在使用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