Ask Your Question
0

How to save ANN_MLP by appending to file containing other data?

asked 2017-10-05 09:22:36 -0600

nmcfarlane gravatar image

updated 2017-10-05 11:41:27 -0600

I'm using OpenCV 3.2. I need to save a trained ANN_MLP network, but it needs to be saved in the same file as other serialised data from the application (the api specifies only one set-up file), so I need a save() method that appends to existing data in a file.

Is there a way to save ANN_MLP by appending to an existing file and then read it back again?

Failing that, is is possible to "train" a network by setting the weight matrices, instead of using train() or load()? This would enable me to simply write/read the matrices that describe the network.

edit retag flag offensive close merge delete

Comments

I have solved the second part of this question: it is possible to create a working network by copying the matrices. The tricky part is that there is no setWeights() method, so you have to copy the weights using:

mlp->getWeights(i).copyTo(mlp2->getWeights(i));

Only copyTo() will actually copy to the internal data of mlp2; assignment and clone() will not work.

nmcfarlane gravatar imagenmcfarlane ( 2017-10-05 11:29:43 -0600 )edit
1

this is the "back door".

what if you use

my_nn->write(some_existing_filestorage);

to save it, and

Ptr<ANN_MLP> new_nn = Algorithm::read<ml::ANN_MLP>(some_existing_filestorage);

to retrieve it ?

berak gravatar imageberak ( 2017-10-05 11:45:55 -0600 )edit

1 answer

Sort by » oldest newest most voted
1

answered 2017-10-06 06:15:15 -0600

nmcfarlane gravatar image

updated 2017-10-06 06:18:33 -0600

berak gravatar image

Thank you, berak. For info, in the simple case of writing and reading, this works:

cv::FileStorage fs;
fs.open("mlp.xml", cv::FileStorage::WRITE);
mlp->write(fs);
fs.release();

mlp2 = ANN_MLP::create();
fs.open("mlp.xml", cv::FileStorage::READ);
mlp2->read(fs.root());
fs.release();

If the network is to be saved as a node in a larger hierarchy, write with:

  fs << "StructureAndWeights" << "{";
  mlp->write(fs);
  fs << "}";

and read with:

 cv::FileNode node0 = fs.root();
 cv::FileNode node1 = node0["StructureAndWeights"];
 mlp2->read(node1);
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2017-10-05 09:22:36 -0600

Seen: 453 times

Last updated: Oct 06 '17