首页 > 解决方案 > Matlab中表格上的K折交叉验证

问题描述

我有一个包含学生信息(数字和分类)的 Matlab 表。这里给出了一个示例:

School = {'GB'; 'UR'; 'GB'; 'GB'; 'UR'};
School = categorical(School);
Age = [14;14;12;16;19];
Relationship = {'yes'; 'yes'; 'no'; 'no'; 'yes'};
Relationship = categorical(Relationship);
Status = {'ft'; 'pt'; 'ft'; 'ft'; 'ft'};
Status = categorical(Status);
Father_Job = {'pol'; 'ser'; 'oth'; 'ele'; 'cle'};
Father_Job = categorical(Father_Job);
Health = [1;2;3;3;5];
Exam = {'pass'; 'pass'; 'fail'; 'fail'; 'pass'};
Exam = categorical(Exam);

T =
School    Age    Relationship    Status    Father_Job    Health    Exam
______    ___    ____________    ______    __________    ______    ____

  GB      14         yes           ft         pol          1       pass
  UR      14         yes           pt         ser          2       pass
  GB      12         no            ft         oth          3       fail
  GB      16         no            ft         ele          3       fail
  UR      19         yes           ft         cle          5       pass

我想使用这些数据来预测和分类考试的通过/失败。我打算使用fitglm进行逻辑回归,并fitcnb制作朴素贝叶斯分类器。我知道这两种方法都可以很好地处理 Matlab 中的分类变量,所以使用我的表应该没有问题,它的分类变量。

但是,当我想使用cvpartitioncrossvalind执行 10 倍交叉验证时,我遇到了问题。当我尝试创建折叠索引时,出现以下错误:使用 statslib.internal.grp2idx 时出错 不支持使用线性索引(一个下标)或多维索引(三个或更多下标)为表下标。使用行下标和变量下标

我的目标是执行以下操作:

% Column 7 (Exam) is the response variable
X = T(:, 1:6);
Y = T(:, 7);

% Create indices of 5-fold cross-validation (here I get errors)
cvpart = cvpartition(Y,'KFold',5);
indices = crossvalind('Kfold',Y,5);

% Create my test and training sets
for i = 1:5
 test = (indices == i); 
 train = ~test;
 Xtrain = X(train,:);
 Xtest = X(test,:);
 Ytrain = Y(train,:);
 Ytest = Y(test,:);
end

% Fit logistic model
mdl = fitglm(Xtrain,Ytrain,'Distribution','binomial')

请问有人对此有意见吗?我知道我可以将分类变量更改为数值变量,但我宁愿不这样做。有没有办法解决?谢谢你。

标签: matlablogistic-regressioncross-validationcategorical-datanaivebayes

解决方案


我认为您的主要问题是您的数据集太小了。您有 n = 5,这甚至不足以创建未经验证的模型。


推荐阅读