MATLAB: Saved classifier forgets its predict function

binarydata importdatabaseMATLABpythonStatistics and Machine Learning Toolbox

In a project I'm training several classifiers in Matlab 2020b, new data though should be processed in python 3.8. To do so I save the trained classifiers as .mat files (simply with "save(classifier_obj)").
In order to allow multiple users (without a matlab licence but with the runtime v9.9 installed) to use the classifiers I store these files as blob in a mysql DB (I know its not the best practice as stated here: https://de.mathworks.com/matlabcentral/answers/84154-storing-a-mat-file-in-mysql-database.).
When accessing, I download the blob file, store it temporaly on disc with these 2 lines in python and pass the file_name to the compiled matlab function (described below)
tmp = open(file_name, "wb")
tmp.write(mat)
In order to classify new data elements I've written this little function and compiled it as python code.
function label=new_classifier_predict(file_name,data)
load(file_name);
label=predict(classifier,data);
My problem now is that the classifier seems to forget its class method "predict"…
File C:\Users\steenbuck\AppData\Local\Temp\steenbuck\mcrCache9.9\new_cl0\new_classifi\classificators\new_classifier_predict.m, line 4, in new_classifier_predict
Method 'predict' is not defined for class 'ClassificationKNN' or is removed from MATLAB's search path.
I'm guessing that the object can't be reconstructed completly and therefore fails.. Strangely this error only occours when running the compiled python file. Matlab 2020b can handle all files as expected.
Is there a way to solve this or to debug and see whats happening the the matlab runtime environment?

Best Answer

Matlab support got the soluition:
For MATLAB Compiler deployed component to be able to correctly load a pretrained classifier from a MAT-file, and for all methods of that classifier to then be available, the correct classifier class definitions actually need to be "available" in the deployed component. For your custom classifier classes, you probably noticed that your custom classes actually need to be compiled into the component at compile time for them to be available at runtime. For built-in classifiers something similar has to be done, we actually need to know at compile time already that you want to work with them such that we can then properly make them available at runtime.
One way to make the compiler aware of these things at compile time is to use %#function pragmas in your code:
So, to make sure that the ClassificationKNN class from the error message is properly available, add:
%#function ClassificationKNN to the code before compilation.
function label=new_classifier_predict(file_name,data)
%#function ClassificationKNN
load(file_name);
label=predict(classifier,data);
Related Question