Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

cv::ml::StatModel::predict not working / neural networks

I'm using iris data set for NN training in OpenCV 3.0.0. Trying to categorize the plants into 2 (I.setosa or non-I.setosa).

This is the main code, not added the some functions:

#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <opencv2/imgproc.hpp>
#include <fstream>  //required for reading the files
#include <algorithm>    // std::random_shuffle

#define NUM_EXAMPLES 150
#define NUM_OUTPUTS 1
#define numVariables 4

using namespace std;
using namespace cv;
using namespace cv::ml;

int main(void)
{
//---------------------  Reading the data and labels from iris.txt ---------------------------------
Mat allData(NUM_EXAMPLES, numVariables, CV_32FC1);
Mat allLabels(NUM_EXAMPLES, NUM_OUTPUTS, CV_32FC1);
readFile("iris.txt", allData, allLabels); //reading from txt file and writing the values to Mat
                         //marking labels of I.setosa as 1.7159, and -1.7159
                          //for the rest  

//building the cv::Ptr<cv::ml::TrainData>
cv::Ptr<cv::ml::TrainData> trainer  = cv::ml::TrainData::create(allData, cv::ml::ROW_SAMPLE, 
allLabels);
trainer->setTrainTestSplitRatio(0.8, true); //Splits the training data into the training and test parts.

//------------------------ Set up NN parameters --------------------
Ptr< ANN_MLP >  nn = ANN_MLP::create();
nn->setActivationFunction(cv::ml::ANN_MLP::SIGMOID_SYM);
nn->setTrainMethod(cv::ml::ANN_MLP::BACKPROP);
nn->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, (int)100000, 1e-6));
Mat layers = cv :: Mat (3 , 1 , CV_32SC1 );
layers . row (0) = cv :: Scalar (4,0) ;
layers . row (1) = cv :: Scalar (3,0) ;
layers . row (2) = cv :: Scalar (1,0) ;
nn->setLayerSizes(layers);

//------------------------ Train the NN --------------------
nn->train(trainer);
Mat inputT(1,4,CV_32FC1,{7.3000002, 2.9000001, 6.3000002, 1.8});
nn->predict(inputT);
}

I'm keep getting "Segmentation fault (core dumped)" error because of the "predict" above. Tried many different things, but still predict does not work. What should I do?

Extra Information:

partial display of the iris.txt file :

5.1 3.8 1.6 0.2 I.setosa
4.6 3.2 1.4 0.2 I.setosa
5.3 3.7 1.5 0.2 I.setosa
5.0 3.3 1.4 0.2 I.setosa
7.0 3.2 4.7 1.4 I.versicolor
6.4 3.2 4.5 1.5 I.versicolor
6.9 3.1 4.9 1.5 I.versicolor
5.5 2.3 4.0 1.3 I.versicolor

partial display of trainer->getTrainSamples() :

[6.5999999, 3, 4.4000001, 1.4;
 5.5, 2.5, 4, 1.3;
 6.5, 3, 5.8000002, 2.2;
 4.4000001, 2.9000001, 1.4, 0.2;
 6.4000001, 2.8, 5.5999999, 2.2;

partial display of trainer->getTrainResponses() :

[-1.7158999;
 -1.7158999;
 -1.7158999;
 1.7158999;
 -1.7158999;