Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving KNN classifier after learning in opencv

Tags:

opencv

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?

like image 232
eng.emooo Avatar asked Jun 24 '12 11:06

eng.emooo


People also ask

How do I export my KNN model?

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().

How do I save my Sklearn KNN model?

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.


3 Answers

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.

like image 82
tOnIp Avatar answered Nov 07 '22 06:11

tOnIp


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.

like image 36
Julia Avatar answered Nov 07 '22 08:11

Julia


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.

like image 24
KobeJohn Avatar answered Nov 07 '22 08:11

KobeJohn