How to load previously stored svm classifier?

2019-06-28 08:04发布

问题:

I'm working with openCV SVM in Visual Studio. (OpenCV 2.4.4.0)

I trained it:

mySVM.train(trainingDataMat, labelsMat, Mat(), Mat(), params);

Saved it:

mySVM.save("classifier.xml");

I'm loading it like this:

CvSVM mySVM1;
mySVM1.load("C:\classifier.xml");
mySVM1.predict(testingDataMat0,result0);

And i want to use in other project. But when i try to load classifier this error bumps all the time:

"Bad argument (The SVM should be trained first) in CvSVM::predict"

Path is correct, and .xml seems correctly stored.

Does anybody know what am I doing wrong or where the problem might be?

classifier.xml:

<?xml version="1.0"?>
<opencv_storage>
<my_svm type_id="opencv-ml-svm">
  <svm_type>C_SVC</svm_type>
  <kernel><type>RBF</type>
    <gamma>5.0625000000000009e-001</gamma></kernel>
  <C>2.5000000000000000e+000</C>
  <term_criteria><epsilon>2.2204460492503131e-016</epsilon>
    <iterations>100</iterations></term_criteria>
  <var_all>3</var_all>
  <var_count>3</var_count>
  <class_count>2</class_count>
  <class_labels type_id="opencv-matrix">
    <rows>1</rows>
    <cols>2</cols>
    <dt>i</dt>
    <data>
      -1 1</data></class_labels>
  <sv_total>10</sv_total>
  <support_vectors>
    <_>
      9.09866020e-002 5.56291997e-001 2.43510995e-002</_>
    <_>
      9.46519971e-001 2.94328004e-001 2.08841003e-002</_>
    <_>
      1. 3.68389994e-001 1.15272999e-002</_>
    <_>
      9.41470027e-001 3.73109013e-001 1.25126000e-002</_>
    <_>
      1. 2.23776996e-001 9.57737025e-003</_>
    <_>
      4.68845010e-001 3.62690985e-002 9.11400989e-002</_>
    <_>
      7.98106015e-001 2.73550004e-002 9.26491022e-002</_>
    <_>
      7.02144980e-001 3.98130007e-002 9.00894031e-002</_>
    <_>
      4.99359012e-001 4.31513004e-002 8.61563012e-002</_>
    <_>
      7.39947975e-001 4.39946018e-002 9.60593969e-002</_></support_vectors>
  <decision_functions>
    <_>
      <sv_count>10</sv_count>
      <rho>-5.7845965027809154e-001</rho>
      <alpha>
        2.5000000000000000e+000 2.5000000000000000e+000
        1.4641912158132706e+000 2.5000000000000000e+000
        2.5000000000000000e+000 -1.4641912158132708e+000
        -2.5000000000000000e+000 -2.5000000000000000e+000
        -2.5000000000000000e+000 -2.5000000000000000e+000</alpha>
      <index>
        0 1 2 3 4 5 6 7 8 9</index></_></decision_functions></my_svm>
</opencv_storage>

回答1:

I had this problem and found that in SVM codes ,at least in OpenCV, predict function uses the same kernel witch is used in train function to determine input class. So when you run predict separately it doesn't know what kind of kernel should it uses. So, I think running train function exactly before predict function is avoidable.