2

I am looking for an example of applying 10-fold cross-validation in neural network.I need something link answer of this question: Example of 10-fold SVM classification in MATLAB

I would like to classify all 3 classes while in the example only two classes were considered.

Edit: here is the code I wrote for iris example

load fisheriris                              %# load iris dataset

k=10;
cvFolds = crossvalind('Kfold', species, k);   %# get indices of 10-fold CV
net = feedforwardnet(10);


for i = 1:k                                  %# for each fold
    testIdx = (cvFolds == i);                %# get indices of test instances
    trainIdx = ~testIdx;                     %# get indices training instances

    %# train 

    net = train(net,meas(trainIdx,:)',species(trainIdx)');
    %# test 
    outputs = net(meas(trainIdx,:)');
    errors = gsubtract(species(trainIdx)',outputs);
    performance = perform(net,species(trainIdx)',outputs)
    figure, plotconfusion(species(trainIdx)',outputs)
end

error given by matlab:

Error using nntraining.setup>setupPerWorker (line 62)
Targets T{1,1} is not numeric or logical.

Error in nntraining.setup (line 43)
    [net,data,tr,err] = setupPerWorker(net,trainFcn,X,Xi,Ai,T,EW,enableConfigure);

Error in network/train (line 335)
[net,data,tr,err] = nntraining.setup(net,net.trainFcn,X,Xi,Ai,T,EW,enableConfigure,isComposite);

Error in Untitled (line 17)
    net = train(net,meas(trainIdx,:)',species(trainIdx)');
Community
  • 1
  • 1
Sadegh
  • 865
  • 1
  • 23
  • 47
  • You need to supply some code first. At the very least show how you are implementing the neural network without cross validation and what parameter you are trying to tune. Also have a look at this answer: http://stackoverflow.com/a/28168462/1011724, all you need to change is the `fun` function – Dan Jan 13 '16 at 15:44
  • I dont have any code.Any DB like Iris is fine. Basically the answer you sent and the link in the question are both fine with SVM. However I dont know how to train and test NN classifier in Matlab. Any specification of classifier doesn't have any importance – Sadegh Jan 13 '16 at 15:48
  • 1
    Stack overflow is not a code writing service. It is a forum to ask for help when you are stuck with a coding problem. You need to attempt this yourself first! Have you read the docs on training a neural net in MATLAB? – Dan Jan 13 '16 at 15:50
  • Yes,Offcourse I tried it myself and I received either unexpected wrong answer or errors. – Sadegh Jan 13 '16 at 15:57
  • Also notice that I didnt ask for a specific code, I just ask for any example using neural network classifier with cross validation applied. – Sadegh Jan 13 '16 at 16:17
  • I also add the code which result in wrong answer – Sadegh Jan 13 '16 at 19:38
  • Why all negative votes? what is wrong with question? I also add the code so please remove the negative votes – Sadegh Jan 13 '16 at 19:45
  • I also add the error given by matlab – Sadegh Jan 13 '16 at 20:23
  • 1
    Your error is because if you look at `species` you will see it is a categorical variable (i.e. not numerical or logical). You need to break it up into 3 [binary dummy variables](http://www.tek-tips.com/faqs.cfm?fid=5136) – Dan Jan 14 '16 at 07:14
  • I also tried to use O variable in the answer with my own code. I receive this error : Grouping variable must be a vector or a character array. – Sadegh Jan 14 '16 at 14:25
  • I ask a similar question here https://stackoverflow.com/questions/34826822/cross-validation-with-knn-classifier-with-external-function – Sadegh Jan 16 '16 at 12:41

1 Answers1

6

It's a lot simpler to just use MATLAB's crossval function than to do it manually using crossvalind. Since you are just asking how to get the test "score" from cross-validation, as opposed to using it to choose an optimal parameter like for example the number of hidden nodes, your code will be as simple as this:

load fisheriris;

% // Split up species into 3 binary dummy variables
S = unique(species);
O = [];
for s = 1:numel(S)
    O(:,end+1) = strcmp(species, S{s});
end

% // Crossvalidation
vals = crossval(@(XTRAIN, YTRAIN, XTEST, YTEST)fun(XTRAIN, YTRAIN, XTEST, YTEST), meas, O);

All that remains is to write that function fun which takes in input and output training and test sets (all provided to it by the crossval function so you don't need to worry about splitting your data yourself), trains a neural net on the training set, tests it on the test set and then output a score using your preferred metric. So something like this:

function testval = fun(XTRAIN, YTRAIN, XTEST, YTEST)

    net = feedforwardnet(10);
    net = train(net, XTRAIN', YTRAIN');

    yNet = net(XTEST');
    %'// find which output (of the three dummy variables) has the highest probability
    [~,classNet] = max(yNet',[],2);

    %// convert YTEST into a format that can be compared with classNet
    [~,classTest] = find(YTEST);


    %'// Check the success of the classifier
    cp = classperf(classTest, classNet);
    testval = cp.CorrectRate; %// replace this with your preferred metric

end

I don't have the neural network toolbox so I am unable to test this I'm afraid. But it should demonstrate the principle.

Dan
  • 45,079
  • 17
  • 88
  • 157
  • Thanks for answer! what do you mean by O in O(:,end+1) = strcmp(species, S{s}); ? it gives an error. – Sadegh Jan 14 '16 at 09:18
  • @WOEITG oops, forgot to initialise it, see my edit. Sorry for the poor variable names, `O` will be your transformed (i.e. into dummy variables) outputs – Dan Jan 14 '16 at 09:20
  • If you're too lazy to create the `O` array yourself, you can load it directly with `[~,t] = iris_dataset;`;-) – hbaderts Jan 14 '16 at 09:26
  • Really? I found this in the [documentation of `patternnet`](http://mathworks.com/help/nnet/ref/patternnet.html) (see example). Maybe it has something to do with different MATLAB versions. – hbaderts Jan 14 '16 at 09:30
  • @hbaderts oh maybe it's part of the NN toolbox which I don't have – Dan Jan 14 '16 at 09:32
  • in first line fischeriris is miss spelled and should change to fisheriris.I saved the function with the name fun.m in the same folder of code but I stil receive an error. – Sadegh Jan 14 '16 at 09:40
  • @WOEITG that is very strange. You are 100% sure that the function `fun` is in it's own m-file (no code before it) call *fun.m* and that it is in the active folder that your script calling it it running from? – Dan Jan 14 '16 at 10:22
  • 1
    using `@(a,b,c,d) fun(a,b,c,d)` instead of `@fun` works – hbaderts Jan 14 '16 at 10:27
  • 1
    @Dan I think it should be `net = feedforwardnet(10);` instead of only `feedforward` – hbaderts Jan 14 '16 at 10:28
  • @hbaderts thanks I'll make those changes. I'm surprised that you need to call `fun` as an anonymous function though – Dan Jan 14 '16 at 11:09
  • Does it work for you? I receive this error : Inputs and targets have different numbers of samples. http://s21.postimg.org/62np2tsh3/Capture2.png – Sadegh Jan 14 '16 at 11:37
  • @WOEITG you will have to debug this, I can't test it as I don't have the toolbox. Check the dimensions of variables like `yNet`, `classNet` and `classTest`. They should be *150*-by-*3*, *150*-by-*1* and *150*-by-*1* respectively. Also note that I did not transpose the inputs to `train` or `net` like you did, maybe you have to, I don't know because I can't test it. – Dan Jan 14 '16 at 12:03
  • I spent time to understand the problem. Non of variables you mentioned is generated. meas and O are 150x4 and 150x3 respectively which seems correct. I think there is something wrong with the way crossval is used with variables inside but I am not sure yet. – Sadegh Jan 14 '16 at 14:19
  • Can't you put a breakpoint inside the `fun` function? You won't see the other variables otherwise, they won't be in scope... – Dan Jan 14 '16 at 14:25
  • I debuged inside the function. Error happens when `net = train(net, XTRAIN, YTRAIN);` is run inside the function. The size of `XTRAIN` and `YTRAIN` are 135x4 and 135X3 respectively. So it doesnt run `yNet = net(XTEST);` and next lines – Sadegh Jan 14 '16 at 14:53
  • @WOEITG so then I guess try transposing them like you had it originally: `net = train(net, XTRAIN', YTRAIN');` – Dan Jan 14 '16 at 14:56
  • transposing as you suggested solve this problem. however there is this error now `Non-singleton dimensions of the two input arrays must match each other.` – Sadegh Jan 14 '16 at 15:02
  • @WOEITG there is no point posting an error if you don't also mention what line it occurs on. Just debug, you probably have to transpose for some other function or transpose back. – Dan Jan 14 '16 at 15:04
  • Sorry I forget to mention the line related to error. Error happens in `yNet = net(XTEST);` I transposed `XTEST` and now it doesnt have the last error. instead new error related to variable `out` inside the function: `Undefined function or variable 'out'.` – Sadegh Jan 14 '16 at 15:10
  • I applogize as I am very consufed. Now after fixing everything said (also I transposed YTEST inside the fucntion), error happens in `cp = classperf(classTest, classNet);` `The classifier output CLASSOUT does not have the same size as the ground truth and there was not any TESTIDX provided.` `classTest` and `classNet` are `15x1` and `3x1` respectively. – Sadegh Jan 14 '16 at 15:24
  • @WOEITG this is still a transposing error I would guess. Try `[~,classNet] = max(yNet',[],2);` and `[~,classTest] = find(YTEST);` – Dan Jan 14 '16 at 15:27
  • exactly. Thank you very much indeed! I try to improve the answer with final confusion matrix and accuracy. – Sadegh Jan 14 '16 at 15:36
  • @Dan in the 'val' variable, what does each of the values signify? – girl101 Aug 08 '16 at 09:09