Confusion Matrix of trained SVM (linear) Model

34 Ansichten (letzte 30 Tage)
Harry
Harry am 19 Mär. 2017
Kommentiert: James Herman am 11 Jul. 2019
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);
%

Antworten (1)

Nanda Gupta
Nanda Gupta am 27 Mär. 2017
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 Kommentare
Alessandro Fascetti
Alessandro Fascetti am 5 Okt. 2018
This command does not work in Matlab R2018a.
James Herman
James Herman am 11 Jul. 2019
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.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by