Naoum Mandrelas
Naoum Mandrelas

Reputation: 258

Accord Machine Learning knn.decide indexOutOfRangeException

I'm trying to use the k-nearest-neighbor that Accord library implements. First of all , I used

        double[][] inputs = new double[15000][];
        int[] outputs = new int[15000];

        for (int list_counter= 0; list_counter < training_set.Count; list_counter ++ ) {
            outputs[list_counter] = (char.Parse(training_set[list_counter].letter));

            double[] input = new double[16];
            for(int i =0; i< 16; i++) {
                input[i] = (double)training_set[list_counter].integers[i];
            }
            inputs[list_counter] = input;
        }

        var knn = new KNearestNeighbors(k: 4);
        knn.NumberOfInputs = 16;
        Console.WriteLine("Learning the algorithm");
        knn.Learn(inputs, outputs);

this piece of code to teach knn the algorithm , I have a 15000 set of integers,which I first convert to double and use as input. Then I have a 15000 set of 1 character strings which I first convert to char to get the integer value , and then classify them as outputs.
Some screenshots of the inputs and the outputs. InputsOutputs

I also set the number of inputs to 16 to avoid this kind of problem. But on this piece of code

            for (int list_counter = 0; list_counter < validation_set.Count; list_counter++) {
               double[] input = new double[16];
               for (int i = 0; i < 16; i++) {
                   input[i] = (double)validation_set[list_counter].integers[i];
               }
               int answer = knn.Decide(input); 

Whenever I try to knn.decide , I get an IndexOutOfRangeException. Which seems strange because I used the exact same logic to insert inputs (an array[15000] of a double[16] array.
Here is a screenshot of the input[] before the program crashesInput before the crash

The decide method documentation didn't help me,but I'll leave the links :
knn decide documentation
knn documentation

EDIT : stack trace

Upvotes: 2

Views: 720

Answers (1)

Naoum Mandrelas
Naoum Mandrelas

Reputation: 258

So ,the answer to this particular problem is weird , and I couldn't find it in the documentation of the knn algorithm.
The problem was that outputs on knn.Learn part must start with 0 and be counting upwards . Converting capital character to int gave me a minimum of 65 ('A') , I changed the first of the code

                outputs[list_counter] = (char.Parse(training_set[list_counter].letter)) -65 ;

and now everything runs like clockwork!

Upvotes: 1

Related Questions