如何预测更接近测试数据的第二类 [英] how to predict second class which is more close to test data

查看:74
本文介绍了如何预测更接近测试数据的第二类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用opencv-2.4(CvSVM)进行分类.对于每个测试数据,它都将预测一个类别作为预测输出.但是我需要找到更接近测试数据的下一类. 有什么办法可以在opencv SVM分类器中找到它?

I am using opencv-2.4 (CvSVM) for classification. For each test data it is predicting one class as predicted output. But I need to find the next class which is more close to the test data. Is there any way to find that in opencv SVM classifier ??

推荐答案

不幸的是,您不能使用当前界面直接执行此操作. 一种解决方案是改为使用库 libsvm .

Unfortunately, you can not do it directly with the current interface. One solution would be to use the library libsvm instead.

您可以在opencv中进行此操作,但这需要一些工作.

You may do it in opencv, but it will require a little bit of work.

首先,您必须知道OpenCV使用"1-against- 1"策略进行多类别分类. 对于N类问题,它将训练N *(N-1)/2个二进制分类器(每对两个类一个),然后使用多数表决选择最可能的类.

First, you must know that OpenCV uses a "1-against-1" strategy for multi-class classification. For a N-class problem, it will train N*(N-1)/2 binary classifier (one for each couple of classes), and then uses a majority vote to choose the most probable class.

您将必须应用每个分类器,并自己进行多数操作以获得所需的内容.

You will have to apply each classifier, and do the majority yourself to get what you want.

以下代码向您展示了如何使用OpenCV 3进行操作(警告:未经测试,可能包含错误,但它为您提供了一个很好的起点).

The code below show you how to do that with OpenCV 3 (warning: it is untested, probably contains errors, but it gives you a good starting point).

Ptr<SVM> svm;
int N;            //number of classes
Mat data;         //input data to classify

Mat sv=svm->getSupportVectors();
Ptr<Kernel> kernel=svm->getKernel();
Mat buffer(1,sv.rows,CV_32F);
kernel->calc(sv.rows, sv.cols , sv.ptr<float>(), data.ptr<float>(), buffer.ptr<float>());  // apply kernel on data (CV_32F vector) and support vectors

Mat alpha, svidx;
vector<int> votes(N, 0);  // results of majority vote will be stored here

int i, j, dfi;
for( i = dfi = 0; i < N; i++ ) 
{
    for( j = i+1; j < N; j++, dfi++ )
    {
        // compute score for each binary svm
        double rho=svm->getDecisionFunction(dfi, alpha, svidx);
        double sum = -rho;
        for( k = 0; k < sv.rows; k++ )
            sum += alpha.at<float>(k)*buffer.at<float>(svidx.at<int>(k));
        // majority vote
        votes[sum > 0 ? i : j]++;
    }
}

此代码改编自Opencv的内部代码此处. 正如David Doria在评论中指出的那样,这是不正确的,因为SVM类中没有定义getKernel函数.我仍然将其保留在此处,因为修改内部OpenCV代码以添加它应该不会太困难,而且显然没有其他方法可以做到这一点.

This code is adapted from the internal code of Opencv here. It is incorrect, as pointed out by David Doria in the comments, since there is no getKernel function defined in the SVM class. I still leave it here, since it should'nt be too difficult to modify the internal OpenCV code to add it, and there is apparently no other way to do it.

这篇关于如何预测更接近测试数据的第二类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆