Confusion Matrix of trained SVM (linear) Model

8 次查看(过去 30 天)
Does anyone know how to plot the confusion matrix after a model has been trained?
I would like to produce similar plots as the ones that can be made with the Classification Learner App.
function [trainedClassifier, validationAccuracy] = trainClassifier(trainingData)
inputTable = trainingData;
predictorNames = {'SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'};
predictors = inputTable(:, predictorNames);
response = inputTable.Species;
isCategoricalPredictor = [false, false, false, false];
template = templateSVM(...
'KernelFunction', 'linear', ...
'PolynomialOrder', [], ...
'KernelScale', 'auto', ...
'BoxConstraint', 1, ...
'Standardize', true);
classificationSVM = fitcecoc(...
predictors, ...
response, ...
Features,...
Labels, 'Learners', template, ...
'Coding', 'onevsone', ...
'ClassNames', {'setosa'; 'versicolor'; 'virginica'});
predictorExtractionFcn = @(t) t(:, predictorNames);
svmPredictFcn = @(x) predict(classificationSVM, x);
trainedClassifier.predictFcn = @(x) svmPredictFcn(predictorExtractionFcn(x));
inputTable = trainingData;
predictorNames = {'SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'};
predictors = inputTable(:, predictorNames);
response = inputTable.Species;
isCategoricalPredictor = [false, false, false, false];
partitionedModel = crossval(trainedClassifier.ClassificationSVM, 'KFold', 5);
validationAccuracy = 1 - kfoldLoss(partitionedModel, 'LossFun', 'ClassifError');
[validationPredictions, validationScores] = kfoldPredict(partitionedModel);
confmat=confusionmat(Features(:,1),validationPredictions);
%

回答(1 个)

Nanda Gupta
Nanda Gupta 2017-3-27
I understand that you are trying to represent a trained model with its validated predictions graphically, similar to the one produced by the Classification Learner App.
Since the model is already trained, you can use the function called “plotconfusion” available in the Neural Network Toolbox, to plot the confusion matrix. This creates and plots the confusion matrix for you. There is no need to use “confusionmat” function in this case. Say, in your example, it would just be
plotconfusion(Features(:,1),validationPredictions);
For more information regarding plotconfusion, please refer,
  2 个评论
James Herman
James Herman 2019-7-11
Alessandro - I figured out why this isn't working for me, the data type of the arguments passed to the function (plotconfusion) needs to be "categorical". Even if you're passing a list of integers you need to convert it using the "categorical" function.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Classification Learner App 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by