ベクトルマシンの多分類libSVMをサポートする


ベクトルマシンの多分類をサポートするには、2つの方法を採用することができる.一対一one vs one 2.一対多one vs rest
1.one vs rest 
clc;
clear all;

[iris_label,iris_data] = libsvmread('iris.scale');% matlab 
% [~,~,labels] = unique(species);   %# labels: 1/2/3
% data = zscore(meas);              %# scale features
numInst = size(iris_data,1);
numLabels = max(iris_label);

%# split training/testing
idx = randperm(numInst);
numTrain = 100;
numTest = numInst - numTrain;
trainData = iris_data(idx(1:numTrain),:); 
testData = iris_data(idx(numTrain+1:end),:);
trainLabel = iris_label(idx(1:numTrain));
testLabel = iris_label(idx(numTrain+1:end));

%# train one-against-all models
model = cell(numLabels,1); % 
for k=1:numLabels
    model{k} = svmtrain(double(trainLabel==k), trainData, '-c 1 -g 0.2 -b 1');
end
%# get probability estimates of test instances using each model
prob = zeros(numTest,numLabels);
for k=1:numLabels
    [~,~,p] = svmpredict(double(testLabel==k), testData, model{k}, '-b 1');
    prob(:,k) = p(:,model{k}.Label==1);    %# probability of class==k
end

%# predict the class with the highest probability
[~,pred] = max(prob,[],2);
acc =sum(pred == testLabel) ./ numel(testLabel)    %# accuracy
C = confusionmat(testLabel, pred)                   %# confusion matrix

2.one vs one 
clc;
clear all;

[iris_label,iris_data] = libsvmread('iris.scale');% matlab 
% [~,~,labels] = unique(species);   %# labels: 1/2/3
% data = zscore(meas);              %# scale features
numInst = size(iris_data,1);
numLabels = max(iris_label);

%# split training/testing
idx = randperm(numInst);
numTrain = 100;
numTest = numInst - numTrain;
trainData = iris_data(idx(1:numTrain),:); 
testData = iris_data(idx(numTrain+1:end),:);
trainLabel = iris_label(idx(1:numTrain));
testLabel = iris_label(idx(numTrain+1:end));

model= svmtrain(trainLabel, trainData, '-c 1 -g 0.2 -b 1');
[predict_label, accuracy, prob] = svmpredict(testLabel,testData, model,'-b 1');
% fprintf(' %d.....
',accuracy);

検索のコピー
検索のコピー