neural_network.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <opencv2/ml/ml.hpp>
  2. using namespace std;
  3. using namespace cv;
  4. using namespace cv::ml;
  5. int main()
  6. {
  7. //create random training data
  8. Mat_<float> data(100, 100);
  9. randn(data, Mat::zeros(1, 1, data.type()), Mat::ones(1, 1, data.type()));
  10. //half of the samples for each class
  11. Mat_<float> responses(data.rows, 2);
  12. for (int i = 0; i<data.rows; ++i)
  13. {
  14. if (i < data.rows/2)
  15. {
  16. responses(i, 0) = 1;
  17. responses(i, 1) = 0;
  18. }
  19. else
  20. {
  21. responses(i, 0) = 0;
  22. responses(i, 1) = 1;
  23. }
  24. }
  25. /*
  26. //example code for just a single response (regression)
  27. Mat_<float> responses(data.rows, 1);
  28. for (int i=0; i<responses.rows; ++i)
  29. responses(i, 0) = i < responses.rows / 2 ? 0 : 1;
  30. */
  31. //create the neural network
  32. Mat_<int> layerSizes(1, 3);
  33. layerSizes(0, 0) = data.cols;
  34. layerSizes(0, 1) = 20;
  35. layerSizes(0, 2) = responses.cols;
  36. Ptr<ANN_MLP> network = ANN_MLP::create();
  37. network->setLayerSizes(layerSizes);
  38. network->setActivationFunction(ANN_MLP::SIGMOID_SYM, 0.1, 0.1);
  39. network->setTrainMethod(ANN_MLP::BACKPROP, 0.1, 0.1);
  40. Ptr<TrainData> trainData = TrainData::create(data, ROW_SAMPLE, responses);
  41. network->train(trainData);
  42. if (network->isTrained())
  43. {
  44. printf("Predict one-vector:\n");
  45. Mat result;
  46. network->predict(Mat::ones(1, data.cols, data.type()), result);
  47. cout << result << endl;
  48. printf("Predict training data:\n");
  49. for (int i=0; i<data.rows; ++i)
  50. {
  51. network->predict(data.row(i), result);
  52. cout << result << endl;
  53. }
  54. }
  55. return 0;
  56. }