Opencv mlp无法使用标记CvANN_MLP :: UPDATE_WEIGHTS

时间:2016-06-05 16:51:11

标签: c++ opencv neural-network

我是使用Opencv的新手,尤其是多层感知器(mlp)。我想多次训练网络。因此,我使用标签CvANN_MLP :: UPDATE_WEIGHTS。因为我不希望我的输入和输出被标准化,所以我使用标签CvANN_MLP :: NO_INPUT_SCALE + CvANN_MLP :: NO_OUTPUT_SCALE。

但代码崩溃时出现错误:OpenCV Error:其中一个参数'在CvANN_MLP :: calc_output_scale中,值超出范围(某些新输出训练矢量分量超出原始范围)

代码:

//creation of the multilayer perceptron
Mat layers = cv::Mat(3, 1, CV_32SC1);
layers.row(0) = Scalar(1);
layers.row(1) = Scalar(2);
layers.row(2) = Scalar(1);

CvANN_MLP mlp;
mlp.create(layers, CvANN_MLP::SIGMOID_SYM, 1, 1);

//the training inputs and outputs
Mat trainingData(2, 1, CV_32FC1);
Mat trainingClasses(2, 1, CV_32FC1);

trainingData.at<float>(Point(0, 0)) = 1;
trainingData.at<float>(Point(0, 1)) = -1;

trainingClasses.at<float>(Point(0, 0)) = 1;
trainingClasses.at<float>(Point(0, 1)) = -1;

//the training params
CvANN_MLP_TrainParams params;
CvTermCriteria criteria;
criteria.max_iter = 1;
criteria.epsilon = 0.00001f;
criteria.type = CV_TERMCRIT_ITER | CV_TERMCRIT_EPS;
params.train_method = CvANN_MLP_TrainParams::BACKPROP;
params.bp_dw_scale = 1.0f;
params.bp_moment_scale = 1.0f;
params.term_crit = criteria;

//seems like whe have to do that in order to initialize the weights
mlp.train(trainingData, trainingClasses, Mat(), Mat(), params, CvANN_MLP::NO_INPUT_SCALE + CvANN_MLP::NO_OUTPUT_SCALE);

for (int i(0); i < 10; i++)
{
    //this is the point where it crashes
    mlp.train(trainingData, trainingClasses, Mat(), Mat(), params, CvANN_MLP::UPDATE_WEIGHTS + CvANN_MLP::NO_INPUT_SCALE + CvANN_MLP::NO_OUTPUT_SCALE);

    for (int j(0); j < trainingData.rows; j++)
    {
        Mat input = trainingData.row(j);
        Mat output(1, 1, CV_32FC1);

        mlp.predict(input, output);

        cout << output.at<float>(0, 0) << " ";
    }
    cout << endl;
}

1 个答案:

答案 0 :(得分:-1)

使用这种方法

Ptr train_data = cv::ml::TrainData::create(trainData, ml::ROW_SAMPLE, trainLabels);