www.gusucode.com > stats 源码程序 matlab案例代码 > stats/PlotPosteriorProbabilityContoursForMultipleClassesUsingSExample.m
%% Plot Posterior Probability Contours for Multiple Classes Using SVM % This example steps through the process of one-versus-all (OVA) % classification to train a multiclass SVM classifier, and then plots % probability contours for each class. To implement OVA directly, see % <docid:stats_ug.bue3oc9 fitcecoc>. % %% % Load Fisher's iris data set. Use the petal lengths and widths. % Copyright 2015 The MathWorks, Inc. load fisheriris X = meas(:,3:4); Y = species; %% % Examine a scatter plot of the data. figure gscatter(X(:,1),X(:,2),Y); title('{\bf Scatter Diagram of Iris Measurements}'); xlabel('Petal length'); ylabel('Petal width'); legend('Location','Northwest'); axis tight %% % Train three binary SVM classifiers that separate each type of iris from % the others. Assume that a radial basis function is an appropriate kernel % for each, and allow the algorithm to choose a kernel scale. It is good % practice to define the class order. classNames = {'setosa'; 'virginica'; 'versicolor'}; numClasses = size(classNames,1); inds = cell(3,1); % Preallocation SVMModel = cell(3,1); rng(1); % For reproducibility for j = 1:numClasses inds{j} = strcmp(Y,classNames{j}); % OVA classification SVMModel{j} = fitcsvm(X,inds{j},'ClassNames',[false true],... 'Standardize',true,'KernelFunction','rbf','KernelScale','auto'); end %% % |fitcsvm| uses a heuristic procedure that involves subsampling to compute % the value of the kernel scale. %% % Fit the optimal score-to-posterior-probability transformation function % for each classifier. for j = 1:numClasses SVMModel{j} = fitPosterior(SVMModel{j}); end %% % Define a grid to plot the posterior probability contours. Estimate the % posterior probabilities over the grid for each classifier. d = 0.02; [x1Grid,x2Grid] = meshgrid(min(X(:,1)):d:max(X(:,1)),... min(X(:,2)):d:max(X(:,2))); xGrid = [x1Grid(:),x2Grid(:)]; posterior = cell(3,1); for j = 1:numClasses [~,posterior{j}] = predict(SVMModel{j},xGrid); end %% % For each SVM classifier, plot the posterior probability contour under the % scatter plot of the data. figure h = zeros(numClasses + 1,1); % Preallocation for graphics handles for j = 1:numClasses subplot(2,2,j) contourf(x1Grid,x2Grid,reshape(posterior{j}(:,2),size(x1Grid,1),size(x1Grid,2))); hold on h(1:numClasses) = gscatter(X(:,1),X(:,2),Y); title(sprintf('Posteriors for %s Class',classNames{j})); xlabel('Petal length'); ylabel('Petal width'); legend off axis tight hold off end h(numClasses + 1) = colorbar('Location','EastOutside',... 'Position',[[0.8,0.1,0.05,0.4]]); set(get(h(numClasses + 1),'YLabel'),'String','Posterior','FontSize',16); legend(h(1:numClasses),'Location',[0.6,0.2,0.1,0.1]);