-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Serialized data format
Alex Taranov edited this page Aug 15, 2016
·
6 revisions
- tiny-cnn saves networks weights in plain text format
- all weights of layers are concatnated from input to output and printed as array of double
Opencv expansion (tiny-dnn version >= 0.1.1)
If you use tiny-cnn with Opencv, than another serialization way existed. To save and load network weights we can use cv::FileStorage. This approach makes possible to save network weights (and, if you add some code, all meta information about network architecture and layers) in *.xml or *.yml files.
To save weights and biases use:
template<typename T>
void saveCNNWeights(const char *filename, tiny_cnn::network<T> &_net) const
{
cv::FileStorage fs(filename, cv::FileStorage::WRITE);
if (fs.isOpened()) {
std::vector<tiny_cnn::float_t> _weights;
std::vector<tiny_cnn::vec_t*> _w;
for(size_t i = 0; i < m_net.depth(); i++) {
// From tiny-cnn docs: number of elements differs by layer types and settings.
// For example, in fully-connected layer with bias term,
// weights[0] represents weight matrix and weights[1] represents bias vector.
_w = m_net[i]->get_weights();
tiny_cnn::vec_t *_v;
for(size_t j = 0; j < _w.size(); j++) {
_v = _w[j];
_weights.insert(_weights.end(), _v->begin(), _v->end());
}
}
fs << "weights" << _weights;
fs.release();
} else {
CV_Error(Error::StsError, "File can't be opened for writing!");
}
}
To load weights and biases:
template<typename T>
void CNNFaceRecognizer::load(const char *filename, tiny_cnn::network<T> &_net)
{
cv::FileStorage fs(filename, cv::FileStorage::READ);
if (fs.isOpened()) {
std::vector<tiny_cnn::float_t> _weights;
fs["weights"] >> _weights;
int idx = 0;
std::vector<tiny_cnn::vec_t*> _w;
for(size_t i = 0; i < m_net.depth(); i++) {
_w = m_net[i]->get_weights();
tiny_cnn::vec_t *_v;
for(size_t j = 0; j < _w.size(); j++) {
_v = _w[j];
for(size_t k = 0; k < _v->size(); k++)
_v->at(k) = _weights[idx++];
}
}
fs.release();
} else {
CV_Error(Error::StsError, "File can't be opened for reading!");
}
}
Do not forget however, that before loading the network you should create it.
© Copyright 2018, tiny-dnn team