ANN OPENCV错误断言失败

时间:2017-02-23 19:18:43

标签: c++ opencv machine-learning neural-network

我正在尝试在QT中使用opencv创建一个简单的ANN网络,并在以后开发它,  我尝试使用简单数据并收到错误消息:OpenCV Error : asserion failed ((unsigned)(i1 *datatype<_tp>::channels)) < unsigned(size.p[1]* channels())) in cv::mat::at

这是我写的代码

#include <iostream>
#include <opencv2/ml.hpp>
#include <opencv/cv.h>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "nnet.h"
using namespace std;
using namespace cv;


int main()
{
string filename="data.csv";
Ptr<cv::ml::TrainData> tdata =     cv::ml::TrainData::loadFromCSV(filename,0,-1,-1);

Mat trainData = tdata->getTrainSamples();
Mat trainLabels = tdata->getTrainResponses();
int numClasses = 3;

Mat hot(trainLabels.rows, numClasses, CV_32F, 0.0f);

for (int i=0; i<trainLabels.rows; i++) {
        int id = (int)trainLabels.at<float>(i);
        hot.at<float>(i, id) = 1.0f;
}

    int input_neurons = 5;
    int hidden_neurons = 5;
    int output_neurons = 3;

    Mat layerSizes = Mat(3, 1, CV_32SC1);
    layerSizes.row(0) = Scalar(input_neurons);
    layerSizes.row(1) = Scalar(hidden_neurons);
    layerSizes.row(2) = Scalar(output_neurons);

    Ptr<cv::ml::ANN_MLP> myNetwork = cv::ml::ANN_MLP::create();

    myNetwork->setLayerSizes(layerSizes);
    myNetwork->setTrainMethod(ml::ANN_MLP::SIGMOID_SYM);
    myNetwork->setTermCriteria(TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 1000, 0.00001f));
    myNetwork->setTrainMethod(ml::ANN_MLP::BACKPROP,0.1f,0.1f);
    myNetwork->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM, 1, 1);

    myNetwork->train(trainData, 0, hot);

    string testfilename="test-data.csv";

    Ptr<cv::ml::TrainData> testdata = cv::ml::TrainData::loadFromCSV(testfilename, 0,0,-1);

        Mat testData = testdata->getTrainSamples();
        Mat testLabels = testdata->getTrainResponses();
        Mat testResults;

        myNetwork->predict(testData, testResults);
        float accuracy = float(countNonZero(testResults == testLabels)) / testLabels.rows;
        printf("%f",accuracy);

return 0;
}

和我拥有的数据集

data.csv包含

1,2,3,7,2
7,1,7,7,5
9,7,5,3,2
12,21,32,71,8

和data-test.csv包含:

1,2,1,1,2,
9,1,2,12,5,
11,28,14,50,8,
3,1,2,12,5,
11,28,24,20,8,

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我找到了我的问题的解决方案,在csv文件中我有3个类,响应值应该在[0..2]之间,我给出随机数5和8所以改变它们解决了这个问题< / p>