1
我想要得到隨機森林的最簡單的例子工作。訓練數據是標記爲0的{0,0}和標記爲1的{1,1}。預測的樣本爲{2,2}。 OpenCV的返回0而不是1。這裏是在C的OpenCV代碼++(main.cpp
):OpenCV的瑣碎的隨機森林不起作用,是不一樣的sklearn
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/ml/ml.hpp>
using namespace std;
using namespace cv;
int main(int argc, char const *argv[]) {
cout << " hi \n";
float trainingData[2][2] = { {0.0, 0.0}, {1.0, 1.0}};
Mat training_data(2, 2, CV_32FC1, trainingData);
float trainingClass[2] = {0.0,1.0};
Mat training_class(2, 1, CV_32FC1, trainingClass);
CvRTrees rtree;
rtree.train(training_data, CV_ROW_SAMPLE, training_class);
float sampleData[2] = {2.0, 2.0};
Mat sample_data(2, 1, CV_32FC1, sampleData);
cout << rtree.predict(sample_data) << " <-- predict\n";
return 0;
}
cmake的文件:
cmake_minimum_required(VERSION 2.8)
project(main)
find_package(OpenCV REQUIRED)
add_executable(main main.cpp)
target_link_libraries(main ${OpenCV_LIBS})
運行:
> cmake .;make;./main
hi
0 <-- predict
爲了比較,這裏是一個蟒蛇的sklearn代碼(rfc.py
):
from sklearn.ensemble import RandomForestClassifier
X = [[0, 0], [1, 1]]
Y = [0, 1]
clf = RandomForestClassifier(n_estimators=10)
clf = clf.fit(X, Y)
print clf.predict([[2., 2.]])
運行:
> python rfc.py
[1]