How to do multi class classification using Support Vector Machines (SVM)

后端 未结 8 1969
孤独总比滥情好
孤独总比滥情好 2021-01-30 16:08

In every book and example always they show only binary classification (two classes) and new vector can belong to any one class.

Here the problem is I have 4 classes(c1,

8条回答
  •  醉话见心
    2021-01-30 16:44

    data=load('E:\dataset\scene_categories\all_dataset.mat');
        meas = data.all_dataset;
        species = data.dataset_label;
        [g gn] = grp2idx(species);                      %# nominal class to numeric
    
    %# split training/testing sets
    [trainIdx testIdx] = crossvalind('HoldOut', species, 1/10);
    %# 1-vs-1 pairwise models
    num_labels = length(gn);
    clear gn;
    num_classifiers = num_labels*(num_labels-1)/2;
    pairwise = zeros(num_classifiers ,2);
    row_end = 0;
    for i=1:num_labels - 1
        row_start = row_end + 1;
        row_end = row_start + num_labels - i -1;
        pairwise(row_start : row_end, 1) = i;
        count = 0;
        for j = i+1 : num_labels        
            pairwise( row_start + count , 2) = j;
            count = count + 1;
        end    
    end
    clear row_start row_end count i j num_labels num_classifiers;
    svmModel = cell(size(pairwise,1),1);            %# store binary-classifers
    predTest = zeros(sum(testIdx),numel(svmModel)); %# store binary predictions
    
    %# classify using one-against-one approach, SVM with 3rd degree poly kernel
    for k=1:numel(svmModel)
        %# get only training instances belonging to this pair
        idx = trainIdx & any( bsxfun(@eq, g, pairwise(k,:)) , 2 );
    
        %# train
        svmModel{k} = svmtrain(meas(idx,:), g(idx), ...
                     'Autoscale',true, 'Showplot',false, 'Method','QP', ...
                     'BoxConstraint',2e-1, 'Kernel_Function','rbf', 'RBF_Sigma',1);
    
        %# test
        predTest(:,k) = svmclassify(svmModel{k}, meas(testIdx,:));
    end
    pred = mode(predTest,2);   %# voting: clasify as the class receiving most votes
    
    %# performance
    cmat = confusionmat(g(testIdx),pred);
    acc = 100*sum(diag(cmat))./sum(cmat(:));
    fprintf('SVM (1-against-1):\naccuracy = %.2f%%\n', acc);
    fprintf('Confusion Matrix:\n'), disp(cmat)
    

提交回复
热议问题