Среда: Ubuntu16.04, C ++, G ++ Compiler, opencv, xgboost Теперь я пытаюсь классифицировать изображения с помощью xgboost (C ++). Удар по коду работает хорошо и дает точность около 98% моих данных. Однако при добавлении некоторого кода, который не имеет отношения к событию, например, «labellist.close ()» или «ifstream imglist (« list.txt »)», прогноз модели xgboost становится неверным, и точность падает до 0,05%. На самом деле добавление любой операции OI файла вызвало бы эту проблему. Код и данные для воспроизведения этой проблемы можно загрузить с https://github.com/mangdian/xgboost_classification_test.git.
Что я пробовал: проверить метку вектора: она остается неизменной проверить результат мата: она остается неизменной
ЯЯ почти уверен, что с файловой операцией ввода-вывода что-то не так, но я понятия не имею, что не так.
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_norm_100.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
//ifstream imglist("list.txt");
//vector<string> path;
//string str;
//while(getline(imglist, str))
// path.push_back(str);
FileStorage fs("mat.xml", FileStorage::READ);
Mat result;
fs["feature"] >> result;
const int rows = result.rows;
const int cols = result.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] = result.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; //checked, nothing wrong with label
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;
}
комментируйтене имеет значения код:
метка прогноза
7879 0 24
7880 7 11
7881 12 11
7882 12 11
7883 7 11
7884 6 4
7885 6 4
Точность: 0,069
раскомментируйте нерелевантный код:
метка прогноза
7879 24 24
7880 11 11
7881 11 11
7882 11 11
7883 11 11
7884 4 4
7885 4 4
Точность: 0,996323