SVM Predict返回一个不大于1或-1的大值

时间:2017-12-20 03:24:50

标签: opencv machine-learning svm

所以我的目标是在轿车和SUV之间对车辆进行分类。我使用的训练图像是轿车和SUV的29 150x200图像,所以我的training_mat是29x30000 Mat,我使用双嵌套for循环来代替.reshape,因为重塑不能正常工作。

写入

labels_mat,使得-1对应于轿车,1对应于SUV。我终于得到svm->训练接受两个Mats,我期望一个新的test_image输入svm->预测会产生-1或1.不幸的是,svm-> predict(test_image)返回一个极端高或低值,如-8.38e08。任何人都可以帮我这个吗?

以下是我的大部分代码:

for (int file_count = 1; file_count < (num_train_images + 1); file_count++) 
{
    ss << name << file_count << type;       //'Vehicle_1.jpg' ... 'Vehicle_2.jpg' ... etc ...
    string filename = ss.str();
    ss.str("");

    Mat training_img = imread(filename, 0);     //Reads the training images from the folder

    int ii = 0;                                 //Scans each column
    for (int i = 0; i < training_img.rows; i++) 
    {
        for (int j = 0; j < training_img.cols; j++)
        {
            training_mat.at<float>(file_count - 1, ii) = training_img.at<uchar>(i, j);  //Fills the training_mat with the read image
            ii++; 
        }
    }
}

imshow("Training Mat", training_mat);
waitKey(0);

//Labels are used as the supervised learning portion of the SVM. If it is a 1, its an SUV test image. -1 means a sedan. 
int labels[29] = { 1, 1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1 };

//Place the labels into into a 29 row by 1 column matrix. 
Mat labels_mat(num_train_images, 1, CV_32S);

cout << "Beginning Training..." << endl;

//Set SVM Parameters (not sure about these values)
Ptr<SVM> svm = SVM::create();
svm->setType(SVM::C_SVC);
svm->setC(.1);
svm->setKernel(SVM::POLY);
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
svm->setGamma(3);
svm->setDegree(3);

cout << "Parameters Set..." << endl;

svm->train(training_mat, ROW_SAMPLE, labels_mat);

cout << "End Training" << endl;

waitKey(0);

Mat test_image(1, image_area, CV_32FC1);        //Creates a 1 x 1200 matrix to house the test image. 

Mat SUV_image = imread("SUV_1.jpg", 0);         //Read the file folder

int jj = 0;
for (int i = 0; i < SUV_image.rows; i++)
{
    for (int j = 0; j < SUV_image.cols; j++)
    {
        test_image.at<float>(0, jj) = SUV_image.at<uchar>(i, j);    
        jj++;
    }
}

//Should return a 1 if its an SUV, or a -1 if its a sedan

float result = svm->predict(test_image);

cout << "Result: " << result << endl;

2 个答案:

答案 0 :(得分:1)

输出不会是-1和1.机器学习方法(如SVM)会将成员资格视为结果的符号。所以负值表示-1,正值表示1.

类似地,一些其他方法,例如逻辑回归方法使用概率来预测成员资格,其中通常为0和1.如果概率<0.5,则其成员资格为0,否则为1.

BTW:你的问题不是C ++问题。

答案 1 :(得分:0)

您忘记将标签填入labels_mat。简单的错误,但它发生在每个人......

Mat labels_mat(num_train_images,1,CV_32S,labels);

这应该没问题。