OpenCV3【神经网络】ANN_MLP

//基于OpenCV提供的样例neural_network.cpp,加入了网络保存和读取
#include 

using namespace std;
using namespace cv;
using namespace cv::ml;

int main()
{
	//create random training data
	Mat_ data(100, 100);//训练数据data
	randn(data, Mat::zeros(1, 1, data.type()), Mat::ones(1, 1, data.type()));//随机生成均值为0,标准差为1的数据data
	imshow("", data); waitKey();//显示data
	//half of the samples for each class
	Mat_ responses(data.rows, 2);//行数代表样本数,2为每个样本对应的标签向量(1,0)或(0,1)
	for (int i = 0; i < data.rows; ++i)
	{
		if (i < data.rows / 2)//前一半数据标签为(1,0)
		{
			responses(i, 0) = 1;
			responses(i, 1) = 0;
		}
		else//后一半数据标签为(1,0)
		{
			responses(i, 0) = 0;
			responses(i, 1) = 1;
		}
	}

	/*
	//example code for just a single response (regression)
	Mat_ responses(data.rows, 1);
	for (int i=0; i layerSizes(1, 3);
	layerSizes(0, 0) = data.cols;
	layerSizes(0, 1) = 20;
	layerSizes(0, 2) = responses.cols;

	Ptr network = ANN_MLP::create();//创建
	network->setLayerSizes(layerSizes);//设置层数
	network->setActivationFunction(ANN_MLP::SIGMOID_SYM, 0.1, 0.1);//激活函数
	network->setTrainMethod(ANN_MLP::BACKPROP, 0.1, 0.1);//训练方法
	Ptr trainData = TrainData::create(data, ROW_SAMPLE, responses);//创建训练数据,ROW_SAMPLE表示data中每行为一个样本

	network->train(trainData);//训练
	if (network->isTrained())//是否训练完成
	{
		printf("Predict one-vector:\n");
		Mat result;
		network->predict(Mat::ones(1, data.cols, data.type()), result);//预测全为1的一个样本,得到结果result
		cout << result << endl;

		printf("Predict training data:\n");
		for (int i = 0; i < data.rows; ++i)
		{
			network->predict(data.row(i), result);//预测训练样本,得到结果result
			cout << result << endl;
		}
	}

	network->save("c:\\s.xml");//保存网络

	Ptr bp = ANN_MLP::load("c:\\s.xml");//创建并加载保存的网络
	//bp->load();
	if (1)//测试加载成功,与训练的网络一致
	{
		printf("Predict one-vector:\n");
		Mat result;
		bp->predict(Mat::ones(1, data.cols, data.type()), result);
		cout << result << endl;

		printf("Predict training data:\n");
		for (int i = 0; i < data.rows; ++i)
		{
			bp->predict(data.row(i), result);
			cout << result << endl;
		}
	}
	Mat I = Mat::ones(10, 10,data.type());
	cout << endl << I << endl;
	putchar(1);
	return 0;
}

 

你可能感兴趣的:(opencv,ANN_MLP,opencv)