mask
mask

Reputation: 549

Opencv 300 - Random Forest Predict returns wrong answer

Do you guys have any idea about what is wrong with the following simple Random Forest example in OpenCV 300 (It always predict "0" which is wrong):

Mat train_data= (Mat_<int>(6,3) << 1, 1, 1, 2, 2, 2, -1, -1, -1, 0, 1, 2, 2, 3, 4, -1, -2, -3);
Mat response = (Mat_<int>(1,6) << 0,0,0,1, 1, 1);

Ptr<TrainData> tdata = TrainData::create(train_data, ROW_SAMPLE, response);

Ptr<RTrees> model;
    model = RTrees::create();
    model->setMaxDepth(4);
    model->setMinSampleCount(5);
    model->setRegressionAccuracy(0);
    model->setUseSurrogates(false);
    model->setMaxCategories(15);
    model->setPriors(Mat());
    model->setCalculateVarImportance(true);
    model->setActiveVarCount(4);
    model->setTermCriteria(TC(100,0.01f));
    model->train(tdata);

Mat sample;
sample = (Mat_<float>(1,3) << 0,0,0);  // if I use <int> I'll get error
cout << model->predict(sample) <<"\n";

sample = (Mat_<float>(1,3) << -4,-5,-6);
cout << model->predict(sample) <<"\n";

sample = (Mat_<float>(1,3) << 9,9,9);
cout << model->predict(sample) <<"\n";

sample = (Mat_<float>(1,3) << 19,20,21);
cout << model->predict(sample) <<"\n";

Thanks,

Upvotes: 2

Views: 445

Answers (1)

belitd
belitd

Reputation: 149

I know I might be a bit late, but I had the same problem with OpenCV 2.4.13 and it seems that OpenCV's RandomTrees algorithm doesn't like classes with value 0,

I mean if one or more elements of your response Matrice is/are 0, the RTree algorithm will always predict 0.

I solved it by replacing all the 0 in response Matrice by another value (e.g. 2 in your case will be ok).

Upvotes: 1

Related Questions