Confusion Matrix of trained SVM (linear) Model
8 views (last 30 days)
Show older comments
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);
%
0 Comments
Answers (1)
Nanda Gupta
on 27 Mar 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 Comments
James Herman
on 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.
See Also
Categories
Find more on Classification Learner App in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!