-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test.cpp
102 lines (87 loc) · 2.47 KB
/
Test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<iostream>
#include<opencv2/opencv.hpp>
#include<xgboost/c_api.h>
#include<fstream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
using namespace cv;
//you should get about 98% accuracy without modifying the code
int save(string pca_file, PCA* pca)
{
FileStorage fs(pca_file, FileStorage::WRITE);
fs << "mean" << pca->mean;
fs << "e_vectors" << pca->eigenvectors;
fs << "e_values" << pca->eigenvectors;
fs.release();
return 1;
}
int load(string pca_file, PCA* pca)
{
FileStorage fs(pca_file, FileStorage::READ);
fs["mean"] >> pca->mean;
fs["e_vectors"] >> pca->eigenvectors;
fs["e_values"] >> pca->eigenvectors;
fs.release();
return 1;
}
int main()
{
BoosterHandle h_booster;
const DMatrixHandle *g_trainHandle = nullptr;
int g_trainHandleLength = 0;
int res = XGBoosterCreate(g_trainHandle, g_trainHandleLength, &h_booster);
res = XGBoosterLoadModel(h_booster, "xgboost.model");
ifstream labellist("label.txt");
vector<float> label;
string line;
int l;
while(getline(labellist, line))
{
stringstream ss;
ss << line;
if(!ss.eof()){
ss >> l;
label.push_back(float(l));
label.push_back(float(l)); //nothing wrong here, should be pushed twice
}
}
//labellist.close() when this line or the following line is added, the prediction gets wrong
FileStorage fs("mat.xml", FileStorage::READ); //loading data
Mat data;
fs["feature"] >> data;
const int rows = data.rows;
const int cols = data.cols;
float **train = new float *[rows];
for (int i = 0; i < rows; i++)
train[i] = new float[cols];
cout<<"start copying"<<endl;
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
train[i][j] = data.at<float>(i,j);
}
}
cout<<"mat to array finished"<<endl;
// convert to DMatrix
DMatrixHandle h_train[1], *h_test=nullptr;
res = XGDMatrixCreateFromMat(reinterpret_cast<float *>(train), rows, cols, -1.0, &h_train[0]);
bst_ulong out_len;
const float *f;
XGBoosterPredict(h_booster, h_train[0], 0,0,&out_len,&f);
int count = 0;
for (unsigned int i=0;i<out_len;i++)
{
cout<<f[i] <<"\t" << label[i]<<endl; //
if(f[i] == label[i]) count++;
}
cout<<"Accuracy: "<<float(count)/rows<<endl;
XGDMatrixFree(h_train[0]);
XGBoosterFree(h_booster);
for(int i=0; i<rows; i++)
delete train[i];
delete train;
return 0;
}