神经网络沉静了多年,突然复活了,根本原因是异或问题得到解决。验证异或也应为实践神经网络的第一步。
异或分为四组: {0,0},{0,1},{1,0},{1,1}
对应结果为: {{0}, {1}, {1}, {0}}
上码:
// ANN_XORDemo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace cv;
using namespace ml;
int main()
{
float output[4][1] = { { 0 },{1.0 },{ 1.0 },{ 0 } };
Mat outputMat(4, 1, CV_32FC1, output);
cout << "output-> " << outputMat << endl;
float input[4][2] = { { 0,0 },{0,1.0 },{ 1.0,0 },{ 1.0,1.0 } };
Mat trainingMat(4, 2, CV_32FC1, input);
cout << "input->" << trainingMat << endl;
Mat layer = (Mat_<int>(1, 3) << 2, 2, 1);
Ptr<ANN_MLP> xor = ANN_MLP::create();
xor->setLayerSizes(layer);//
xor->setActivationFunction(ANN_MLP::SIGMOID_SYM);
xor->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON));
xor->setTrainMethod(ANN_MLP::BACKPROP, 0.1);
Ptr<TrainData> trData = TrainData::create(trainingMat, ROW_SAMPLE, outputMat);
xor->train(trData);
Mat sample = (Mat_<float>(1, 2) << 1, 1);
Mat response;
xor->predict(sample, response);
cout << "sample-> " << sample << endl;
cout << "1,1 ->" << response << endl;
sample = (Mat_<float>(1, 2) << 0, 1);
xor->predict(sample, response);
cout << "sample-> " << sample << endl;
cout << "0,1 ->" << response << endl;
sample = (Mat_<float>(1, 2) << 1, 0);
xor->predict(sample, response);
cout << "sample-> " << sample << endl;
cout << "1,0 ->" << response << endl;
sample = (Mat_<float>(1, 2) << 0, 0);
xor->predict(sample, response);
cout << "sample-> " << sample << endl;
cout << "0,0 ->" << response << endl;
return 0;
}
结论:{1,1},{0,0}得到结果为0.001…, {1,0},{0,1}的结果为0.999….结果分别非常逼近异或结果0,1.识别率为100%。