[Python] Are SVM models trained with OpenCV (.xml) and scikit-learn (.pkl) identical if...

Discussão em 'Python' iniciado por Stack, Julho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I’m training a Support Vector Machine (SVM) classifier using both OpenCV’s cv2.ml.SVM (with RBF kernel) and scikit-learn’s sklearn.svm.SVC. I’m using the same training data and same hyperparameters (C, gamma) in both cases.

    My goal: To evaluate if the models are functionally identical, i.e., they produce the same predictions (or at least similar decision function outputs).

    Questions:


    1. Will .pkl (scikit-learn) and .xml (OpenCV) models behave identically if trained under the same conditions?


    2. If not identical, what are the expected differences (e.g. precision, decision boundary shifts)?


    3. Are there any tricks to make their decision scores or probabilities align (e.g. matching normalization or sigmoid calibration)?

    Training with OpenCV:

    import cv2
    svm = cv2.ml.SVM_create()
    svm.setKernel(cv2.ml.SVM_RBF)
    svm.setType(cv2.ml.SVM_C_SVC)
    svm.setC(10)
    svm.setGamma(0.01)
    svm.train(X.astype(np.float32), cv2.ml.ROW_SAMPLE, y.astype(np.int32))
    svm.save("svm_model_opencv.xml")


    Training with sk-learn:

    from sklearn.svm import SVC
    model = SVC(C=10, gamma=0.01, kernel='rbf', probability=True)
    model.fit(X, y)
    joblib.dump(model, "svm_model_sklearn.pkl")


    According to this, it seems the models should be statistically equal, although not bit-identical.

    Continue reading...

Compartilhe esta Página