Search code examples
machine-learningscikit-learncoremlcoremltoolsfacenet

Adding labels while converting SVC FaceClassification model to CoreML using, converters.sklearn.convert


I have trained a model to classify faces based on FaceNet, and while I am trying to convert the model to CoreML model using converters.sklearn.convert, I do not get class labels embedded to it by default, how can I add class labels to my CoreML model.

This my current script that converts the model

classFeatureNames = ("Prediction","Probability")
coreml_model = ct.converters.sklearn.convert(model,input_features='inputArray', output_feature_names=classNames)
coreml_model.save("celebritySix.mlmodel")

Model generated using above script returns me labels as, [0,1,2,3,4,5] while I am expecting the respective name of person detected.


Solution

  • From the coremltools convert docs:

    "If it is a classifier, output_feature_names should be a 2-tuple of names giving the top class prediction and the array of scores for each class (defaults to “classLabel” and “classScores”)."

    Most scikit-learn estimators have a classes_ attribute where labels are stored. Either the model was not trained with the right class labels, or coremltools is not correctly applying the attribute when converting.

    MRE with Y / N labels:

    import numpy as np
    from sklearn.datasets import make_classification
    from sklearn.svm import SVC
    import coremltools
    
    X, y = make_classification(n_clusters_per_class=1, n_informative=4, n_classes=2)
    y_new = np.zeros_like(y, dtype=np.str_)
    y_new[y == 0] = "N"
    y_new[y == 1] = "Y"
    
    clf = SVC().fit(X, y_new)
    # clf.classes_
    # ['N' 'Y']
    
    coreml_model = coremltools.converters.sklearn.convert(clf)
    coreml_model.save("demo_output.mlmodel")