我正在使用BOW模型和SVM开发图像分类项目。 我想要找出SVM的预测概率,但是在opencv svm中没有这样的功能。有什么方法可以实现吗?我想要找出n类SVM的预测概率。
不,您无法使用CvSVM进行此操作。OpenCV的SVM实现基于一个非常旧的libsvm版本。请下载最新版本的libsvm并使用它。当然,您需要编写一个包装器来转换数据格式。详见http://www.csie.ntu.edu.tw/~cjlin/libsvm/
如@Bull所建议的,OpenCV中没有实现预测概率。但是有一种很好的方法可以访问底层libsvm
来获得它。博客上有详细说明,代码片段如下:
注意:此函数加载模型,因此不要在外部加载它。
#include "svm.h"
...
void predict(string modelPath, Mat& hist) {
const char *MODEL_FILE = modelPath.c_str();
if ((this->SVMModel = svm_load_model(MODEL_FILE)) == 0) {
this->modelLoaded = false;
fprintf(stderr, "Can't load SVM model %s", MODEL_FILE);
return;
}
struct svm_node *svmVec;
svmVec = (struct svm_node *)malloc((hist.cols+1)*sizeof(struct svm_node));
int j;
for (j = 0; j < hist.cols; j++) {
svmVec[j].index = j+1;
svmVec[j].value = hist.at<float>(0, j);
}
svmVec[j].index = -1; // this is quite essential. No documentation.
double scores[8]; // suppose there are eight classes
if(svm_check_probability_model(SVMModel)) {
svm_predict_probability(SVMModel, svmVec, scores);
}
}
你可以尝试生成混淆矩阵,这将告诉你每个图像属于任何类别的概率。 混淆矩阵
这里有一段我找到的代码片段,虽然它不完整,但可能会给你一些想法:
map<string,map<string,int> > confusion_matrix; // confusionMatrix[classA][classB] = number_of_times_A_voted_for_B;
map<string,CvSVM> classes_classifiers; //This we created earlier
vector<string> files; //load up with images
vector<string> classes; //load up with the respective classes
for(..loop over a directory?..) {
Mat img = imread(files[i]),resposne_hist;
vector<KeyPoint> keypoints;
detector->detect(img,keypoints);
bowide->compute(img, keypoints, response_hist);
float minf = FLT_MAX; string minclass;
for (map<string,CvSVM>::iterator it = classes_classifiers.begin(); it != classes_classifiers.end(); ++it) {
float res = (*it).second.predict(response_hist,true);
if (res < minf) {
minf = res;
minclass = (*it).first;
}
}
confusion_matrix[minclass][classes[i]]++;
}
我还没有测试过它,所以如果您能让它工作,我将很感激您在此处沟通:)