I used OpenCV KNN classifier and after training it I need to save the classifier to be able to use in testing stage. I found that knn.save()
is not implemented in OpenCV. What should do?
Generating Model First, import the KNeighborsClassifier module and create KNN classifier object by passing argument number of neighbors in KNeighborsClassifier() function. Then, fit your model on the train set using fit() and perform prediction on the test set using predict().
You can use the pickle operation to serialize your machine learning algorithms and save the serialized format to a file. Later you can load this file to deserialize your model and use it to make new predictions.
In k-NN, save and write is not implemented because there is no trainning. What does train method is only store all the samples. So no "model" is infered, then nothing must be saved but all the samples.
In opencv 3.0, knn->save("train.yml") is implemented,,,
Although I couldn't get the load function to work but you can easily read the model from file using FIleStorage and as stated above, in knn the model is basically the features so you always just store the Mat features to file then load later.
Too long for comment, so I'm posting here. This is not a full solution, so anyone who knows exactly how to do it: please share a better answer
I have looked and can't find any direct implementation. However, I found this guy (lots of good stuff on his blog) who figured out how to read these giant sets of trained classifiers which include K Nearest Neighbor.
You may be able to use his method to implement write and read for CvKNearest.
By the way, if my weak c++ understanding is correct, save
and read
are already implemented for you, and only write
and read
actually need to be implemented.
For example with CvBoost::save
:
(boost.cpp) CvBoost::save
--> (inner_functions.cpp) CvStatModel::save
--> (boost.cpp) CvBoost::write
In the same way you would need to add this function:
(knearest.cpp) CvBoost::write
Sorry I couldn't find something more concrete. I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With