How to fix "Use fitcecoc to train a linear model with more than 2 classes" error when using fitcsvm on multiclass data?
Show older comments
I am performing classification on a multi-class biometric dataset with multiple class labels. When training a linear SVM model inside a cross-validation loop using fitcsvm:
mdl = fitcsvm(X_train, Y_train, 'KernelFunction', 'linear', 'Standardize', true);
MATLAB returns the following runtime error:
Error using ClassificationSVM.prepareData (line 721)
Use fitcecoc to train a linear model with more than 2 classes.
Error in classreg.learning.FitTemplate/fit (line 247)
Error in ClassificationSVM.fit (line 261)
Error in fitcsvm (line 342)
Why does fitcsvm restrict to binary classification, and how do I properly configure fitcecoc with templateSVM for multi-class classification with a linear kernel?
1 Comment
Torsten
on 10 Oct 2026
Answer from AI:
In MATLAB, the fitcsvm function strictly restricts classification to binary (two-class) or one-class problems. Mathematically, standard Support Vector Machines are inherently formulated to find an optimal separating hyperplane between exactly two classes. MATLAB adheres directly to this definition in fitcsvm rather than combining multiple inner binary models automatically. [1, 2]
To handle multi-class datasets, you must use Error-Correcting Output Codes (ECOC), which break down your multi-class problem into a sequence of multiple binary problems using a framework like One-vs-One (OVO) or One-vs-All (OVA). [1, 2, 3]
Correcting the Configuration using fitcecoc and templateSVM
To train your multi-class linear SVM model within your cross-validation loop without hitting errors, use the templateSVM function to configure your binary learner. Then, pass that configuration template into fitcecoc. [1]
Here is how you can correctly rewrite your MATLAB code:
matlab
% 1. Create a template configuring the binary linear SVM learners
svm_template = templateSVM(...
'KernelFunction', 'linear', ...
'Standardize', true);
% 2. Train the multi-class ECOC model using the template
mdl = fitcecoc(X_train, Y_train, ...
'Learners', svm_template, ...
'Coding', 'onevsone'); % 'onevsone' is default, or use 'onevsall'
Alternative Approach for High-Dimensional Linear Multi-Class Data
If your biometric dataset consists of a very high number of features (e.g., thousands of gene expressions or pixel vectors), you can alternatively use templateLinear. This utilizes the faster stochastic gradient descent or coordinate descent algorithms via fitclinear internally, which trains significantly faster on high-dimensional text or biometric matrices. [1, 2, 3, 4]
matlab
% Fast linear multi-class option for high-dimensional data
linear_template = templateLinear('Learner', 'svm');
mdl = fitcecoc(X_train, Y_train, 'Learners', linear_template);
Configuration Summary
Feature / Configuration fitcsvm fitcecoc with templateSVM
Max Class Support Binary (2 classes max) Multi-class (unlimited classes)
Underlying Mechanism Solves a single optimization problem Spawns an ensemble of binary learners
Kernel Flexibility Supports linear, gaussian, Inherits any kernel from the SVM template
polynomial
Coding Options N/A onevsone (default) or onevsall
Answers (1)
There are several ways to see how to configure fitcecoc for multi-class classification:
- Consult the MATLAB documentation
- Build the model and generate code from the Classification Learner App
- Consult generative AI
More about option 2: The Classification Learner app can be used to build the desired model, and to generate code so that you can see how to "properly configure fitcecoc with templateSVM for multi-class classification with a linear kernel".
% Load 3-class Fisher iris data
t=readtable("fisheriris.csv");
% Start Classfication Learner app.
classificationLearner(t,"Species")
Once the app is open, start the session, then select the "Linear SVM" model preset. Train that "Linear SVM" model, then, with that model selected, select "Generate Function" in the export options in order to generate code. Here is the code that was generated from R2026b for a "Linear SVM" model for the 3-class Fisher Iris dataset:
function [trainedClassifier, validationAccuracy] = trainClassifier(trainingData)
% [trainedClassifier, validationAccuracy] = trainClassifier(trainingData)
% Returns a trained classifier and its accuracy. This code recreates the
% classification model trained in Classification Learner app. Use the
% generated code to automate training the same model with new data, or to
% learn how to programmatically train models.
%
% Input:
% trainingData: A table containing the same predictor and response
% columns as those imported into the app.
%
%
% Output:
% trainedClassifier: A struct containing the trained classifier. The
% struct contains various fields with information about the trained
% classifier.
%
% trainedClassifier.predictFcn: A function to make predictions on new
% data.
%
% validationAccuracy: A double representing the validation accuracy as
% a percentage. In the app, the Models pane displays the validation
% accuracy for each model.
%
% Use the code to train the model with new data. To retrain your
% classifier, call the function from the command line with your original
% data or new data as the input argument trainingData.
%
% For example, to retrain a classifier trained with the original data set
% T, enter:
% [trainedClassifier, validationAccuracy] = trainClassifier(T)
%
% To make predictions with the returned 'trainedClassifier' on new data T2,
% use
% [yfit,scores] = trainedClassifier.predictFcn(T2)
%
% T2 must be a table containing at least the same predictor columns as used
% during training. For details, enter:
% trainedClassifier.HowToPredict
% Auto-generated by MATLAB on 19-Oct-2026 16:23:36
% Extract predictors and response
% This code processes the data into the right shape for training the
% model.
inputTable = trainingData;
predictorNames = {'SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'};
predictors = inputTable(:, predictorNames);
response = inputTable.Species;
isCategoricalPredictor = [false, false, false, false];
classNames = {'setosa'; 'versicolor'; 'virginica'};
% Train a classifier
% This code specifies all the classifier options and trains the classifier.
template = templateSVM(...
'KernelFunction', 'linear', ...
'PolynomialOrder', [], ...
'KernelScale', 'auto', ...
'BoxConstraint', 1, ...
'Standardize', true);
classificationSVM = fitcecoc(...
predictors, ...
response, ...
'Learners', template, ...
'Coding', 'onevsone', ...
'ClassNames', classNames);
% Create the result struct with predict function
predictorExtractionFcn = @(t) t(:, predictorNames);
svmPredictFcn = @(x) predict(classificationSVM, x);
trainedClassifier.predictFcn = @(x) svmPredictFcn(predictorExtractionFcn(x));
% Add additional fields to the result struct
trainedClassifier.RequiredVariables = {'SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'};
trainedClassifier.ClassificationSVM = classificationSVM;
trainedClassifier.About = 'This struct is a trained model exported from Classification Learner R2026b.';
trainedClassifier.HowToPredict = sprintf('To make predictions on a new table, T, use: \n [yfit,scores] = c.predictFcn(T) \nand replace ''c'' with the name of the variable that is this struct, for example: ''trainedModel''. \n \nThe table, T, must contain the variables returned by: \n c.RequiredVariables \nVariable formats (for example, matrix/vector, datatype) must match the original training data. \nAdditional variables are ignored. \n \nFor more information, see <a href="matlab:helpview(fullfile(docroot, ''stats'', ''stats.map''), ''appclassification_exportmodeltoworkspace'')">How to predict using an exported model</a>.');
% Extract predictors and response
% This code processes the data into the right shape for training the
% model.
inputTable = trainingData;
predictorNames = {'SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'};
predictors = inputTable(:, predictorNames);
response = inputTable.Species;
isCategoricalPredictor = [false, false, false, false];
classNames = {'setosa'; 'versicolor'; 'virginica'};
% Perform cross-validation
partitionedModel = crossval(trainedClassifier.ClassificationSVM, 'KFold', 5);
% Compute validation predictions
[validationPredictions, validationScores] = kfoldPredict(partitionedModel);
% Compute validation accuracy
validationAccuracy = 1 - kfoldLoss(partitionedModel, 'LossFun', 'ClassifError');
In the above code, you can see the configuration of fitcecoc using templateSVM with KernelFunction='linear'. A model built from this code has three Binary Learners, as seen in the list of three "CompactClassificationSVM" models below, which are wrapped into a single ClassificationECOC object.
% Train model using the above function. The model is returned inside a
% struct, just like for models that are exported from the Classification
% Learner app.
mdl = trainClassifier(t);
% Look at the model contents
mdl.ClassificationSVM.BinaryLearners
ans =
3×1 cell array
{1×1 classreg.learning.classif.CompactClassificationSVM}
{1×1 classreg.learning.classif.CompactClassificationSVM}
{1×1 classreg.learning.classif.CompactClassificationSVM}
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!