Whats the problem with my ANN_MLP?
Guys... I'm using the ANN_MLP to predict values like a simple regression.
But, don't know why, isn't working.
My code >> http://pastebin.com/nrczCHxW The output from this code >> http://pastebin.com/BWCY9ZFp
It's should work like this: Train with random numbers and random labels, like ordened pairs (x,y). Test with the first fours elements on the training set. The output should be the first fours elements from the label set...
Someone can help me??
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
using namespace cv;
using namespace cv::ml;
using namespace std;
int main( int argc, char** argv ){
Mat matTrainFeatures(100,1,CV_32F);
randu(matTrainFeatures,0,100);
Mat matTrainLabels(100,1,CV_32F);
randu(matTrainLabels,0,100);
Mat matSample(4,1,CV_32F);
//randu(matSample,0,100);
matSample.at<float>(0,0) = matTrainFeatures.at<float>(0,0);
matSample.at<float>(1,0) = matTrainFeatures.at<float>(1,0);
matSample.at<float>(2,0) = matTrainFeatures.at<float>(2,0);
matSample.at<float>(3,0) = matTrainFeatures.at<float>(3,0);
Mat matSampleLabels(1,1,CV_32F);
Mat matResults(4,1,CV_32F);
//Mat matResults(5,1,CV_32F);
Ptr<TrainData> trainingData;
trainingData=TrainData::create(matTrainFeatures,ROW_SAMPLE,matTrainLabels);
Ptr<ANN_MLP> lr = ANN_MLP::create();
Mat layers(3,1,CV_32FC1);
layers.row(0) = 1;
layers.row(1) = 100;
layers.row(2) = 1;
lr->setBackpropMomentumScale(0.05f);
lr->setLayerSizes(layers);
lr->setBackpropWeightScale(0.05f);
lr->setActivationFunction(ANN_MLP::SIGMOID_SYM, 1, 1);
lr->setTrainMethod(ANN_MLP::BACKPROP, 0.001);
lr->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS, 300, FLT_EPSILON));
//lr->train(trainingData);
for(int j = 0; j < 12; j++){
for(int i = 0; i < matTrainFeatures.rows; i++){
lr->train(matTrainFeatures.row(i),ROW_SAMPLE,matTrainLabels.row(i));
}
}
lr->predict(matSample,matResults);
//Just checking the settings
cout<<"Training data: "<<endl
<<"getNSample\t"<<trainingData->getNSamples()<<endl
<<"getSamples\n"<<trainingData->getSamples()<<endl
<<"getResponses\n"<<trainingData->getTrainResponses()<<endl
<<endl;
//confirming sample order
cout<<"matSample: "<<endl
<<matSample<<endl
<<endl;
//displaying the results
cout<<"matResults: "<<endl
<<matResults<<endl
<<endl;
return 0;
}
you should not call train multiple times on rows, but only once with the full trainData matrix.
@berak still not working... Change the multiple call
To
Now, the output is
matSample: [53.028278; 19.925919; 40.105942; 81.438507]
matResults: [52.965919; 48.013771; 51.669022; 51.085236]
When the correct answer would be [84.443771; 3.7859535; 72.47551; 55.815529;]