Effacer les filtres
Effacer les filtres

Confusion Matrix of trained SVM (linear) Model

12 vues (au cours des 30 derniers jours)
Harry
Harry le 19 Mar 2017
Commenté : James Herman le 11 Juil 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);
%

Réponses (1)

Nanda Gupta
Nanda Gupta le 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 commentaires
Alessandro Fascetti
Alessandro Fascetti le 5 Oct 2018
This command does not work in Matlab R2018a.
James Herman
James Herman le 11 Juil 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.

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by