Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Hi berak,

solved the problem using the same data. I basically removed the setMethod, setBackpropMomentumScale, setBackpropWeightscale, setTermCriteria and it worked. I dont know why but will like someone to explain. Here is the code below:

  int inputLayerSize = 2;
int outputLayerSize = 1;
int numSamples = 3;
int hiddenLayer = 3;
vector<int> layerSizes = { inputLayerSize,hiddenLayer, outputLayerSize };
Ptr<ml::ANN_MLP> nnPtr = ml::ANN_MLP::create();
nnPtr->setLayerSizes(layerSizes);
nnPtr->setActivationFunction(ANN_MLP::SIGMOID_SYM);
//nnPtr->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM);
/*nnPtr->setTrainMethod(ml::ANN_MLP::BACKPROP);
nnPtr->setBackpropMomentumScale(0.1);
nnPtr->setBackpropWeightScale(0.1);
nnPtr->setTermCriteria(TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 100, 1e-4));*/

Mat samples(Size(inputLayerSize, numSamples), CV_32F);
samples.at<float>(Point(0, 0)) = 0.3f;
samples.at<float>(Point(1, 0)) = 1.0f;
samples.at<float>(Point(0, 1)) = 0.2f;
samples.at<float>(Point(1, 1)) = 0.2f;
samples.at<float>(Point(0, 2)) = 1.0f;
samples.at<float>(Point(1, 2)) = 0.4f;
Mat responses(Size(outputLayerSize, numSamples), CV_32F);
responses.at<float>(Point(0, 0)) = 0.75f;
//responses.at<float>(Point(0, 1)) = 0.64f;
responses.at<float>(Point(0, 1)) = 0.82f;
//responses.at<float>(Point(1, 1)) = 0.74f;
responses.at<float>(Point(0, 2)) = 0.93f;
//responses.at<float>(Point(2, 1)) = 0.84f;

cout << "samples:\n" << samples << endl;
cout << "\nresponses:\n" << responses << endl;

if (!nnPtr->train(samples, ml::ROW_SAMPLE, responses))
    return 1;
cout << "\nweights[0]:\n" << nnPtr->getWeights(0) << endl;
cout << "\nweights[1]:\n" << nnPtr->getWeights(1) << endl;
cout << "\nweights[2]:\n" << nnPtr->getWeights(2) << endl;
cout << "\nweights[3]:\n" << nnPtr->getWeights(3) << endl;

Mat output;
Mat samplestest(Size(inputLayerSize, 1), CV_32F);
samplestest.at<float>(Point(0, 0)) = 0.8f;
samplestest.at<float>(Point(1, 0)) = 0.6f;
//samplestest.at<float>(Point(0, 2)) = 0.3f;
nnPtr->predict(samplestest, output);
cout << "\noutput:\n" << output << endl;

and the output is given below:

samples: [0.30000001, 1; 0.2, 0.2; 1, 0.40000001]

responses: [0.75; 0.81999999; 0.93000001]

weights[0]: [2.809757458984826, -1.404878743448629, 2.941742042246543, -1.568929097965231]

weights[1]: [-0.2094534488630105, 0.5412198073856522, 1.658734440612611; -0.8916550488630105, -1.139978207385652, -0.7469871593873889; 0.7505247417458868, 0.7944425035100793, -0.1239852716789556]

weights[2]: [-0.3488449412441831; 0.8637626791966008; 1.178125967026814; -0.2092970630454225]

weights[3]: [0.09473684586976705, 0.8400000035762786]

output: [0.88864398]