Snippets

Amin Ahmadi OpenCV ANN MLP Example

Created by Amin Ahmadi
#include <stdio.h>
#include <vector>
#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    auto trainData = cv::ml::TrainData::loadFromCSV("iris_one_hot_encoded.data",
                                                    0,
                                                    4,
                                                    7);

    trainData->setTrainTestSplitRatio(0.75, true);

    int nFeatures = trainData->getNVars();
    int nClasses = trainData->getResponses().cols;

    Mat_<int> layers(4,1);
    layers(0) = nFeatures;     // input
    layers(1) = nClasses * 32; // hidden
    layers(2) = nClasses * 16; // hidden
    layers(3) = nClasses;      // output,

    auto ann = ml::ANN_MLP::create();
    ann->setLayerSizes(layers);
    ann->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM, 0, 0);
    ann->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 500, 0.0001));
    ann->setTrainMethod(ml::ANN_MLP::BACKPROP, 0.0001);
    ann->train(trainData);

    auto testSamples = trainData->getTestSamples();
    auto testResponses = trainData->getTestResponses();

    Mat result;
    ann->predict(testSamples, result);

    float error = 0.0;
    for(int i=0; i<result.rows; ++i)
    {
        double minVal, maxVal;
        int minIdx, maxIdx;
        cv::minMaxIdx(result.row(i).t(), &minVal, &maxVal, &minIdx, &maxIdx);
        int prediction = maxIdx;
        cv::minMaxIdx(testResponses.row(i).t(), &minVal, &maxVal, &minIdx, &maxIdx);
        int testResponse = maxIdx;

        if(prediction != testResponse)
            error += 1.0;
    }

    float errorRate = error / testSamples.rows;
    float accuracy = 1.0 - errorRate;

    std::cout << "Error = " << errorRate << std::endl;
    std::cout << "Accuracy = " << accuracy << std::endl;
}

Comments (0)