cross-validation for decision tree with matlab
Afficher commentaires plus anciens
data_label={'Revenu','Propriete','Credit ','Classe'};
my_data={'Eleve','Superieur','Non','C1';
'Eleve','Superieur','Oui','C2';
'Eleve','Superieur','Non','C1';
'Eleve','Inferieur','Oui','C2';
'Moyen','Superieur','Non','C1';
'Moyen','Superieur','Oui','C2';
'Moyen','Inferieur','Non','C2';
'Moyen','Inferieur','Oui','C2';
'Faible','Inferieur','Non','C3';
'Faible','Inferieur','Oui','C3'};
and the code for cross-validation:
indices = crossvalind('Kfold',my_data(:,end),10);
cp = classperf(my_data(:,end));
for i = 1:10
test = (indices == i); train = ~test;
class = classify(my_data(test,:),my_data(train,:),my_data(train,:));
classperf(cp,class,test)
end
cp.ErrorRat
But i have this error:
Index exceeds matrix dimensions.
Error in test (line 23)
class = classify(my_data(tests,:),my_data(train,:),data_label(train,:));
Please helppppp !!!!
Réponses (1)
Saurabh
le 30 Mai 2025
The error arises because 'classify' expects numerical input, but the data provided is in a cell array of strings.
Resolution Steps:
- Convert Cell Array to Table:
data_label = {'Revenu','Propriete','Credit','Classe'};
my_data_table = cell2table(my_data, 'VariableNames', data_label);
- Seprate Features and Labels
features = my_data_table(:, 1:end-1);
labels = my_data_table.Classe;
- Convert Categorical Variables to Numeric:
features_array = table2array(features);
features_categorical = categorical(features_array);
features_numeric = dummyvar(features_categorical);
- Perform 10-Fold Cross-Validation:
indices = crossvalind('Kfold', labels, 10);
cp = classperf(labels);
for i = 1:10
test = (indices == i);
train = ~test;
class = classify(features_numeric(test, :), features_numeric(train, :), labels(train));
classperf(cp, class, test);
end
error_rate = cp.ErrorRate;
This approach ensures compatibility with the 'classify' function by providing numerical inputs and properly formatted labels.
I hope this helps.
Catégories
En savoir plus sur Get Started with MATLAB dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!