支持向量机多分类可以采用两种方式,1.一对一 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);%个数 150 numLabels = max(iris_label);%个数3 %# split training/testing idx = randperm(numInst); %随机选择数字,打乱次序 numTrain = 100;%训练个数100 numTest = numInst - numTrain;%测试个数50 trainData = iris_data(idx(1:numTrain),:); %从打乱后的数字选择前100个 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); %模型的个数3个 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
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.....\n',accuracy);
参考:http://blog.csdn.net/xiaoding133/article/details/7676599