cross-validation for decision tree with matlab

조회 수: 4 (최근 30일)
chikilon
chikilon 2017년 3월 15일
답변: Saurabh 2025년 5월 30일
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 !!!!

답변 (1개)

Saurabh
Saurabh 2025년 5월 30일
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.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by