nok / sklearn-porter

Transpile trained scikit-learn estimators to C, Java, JavaScript and others.
BSD 3-Clause "New" or "Revised" License
1.28k stars 170 forks source link

java.lang.ArrayIndexOutOfBoundsException in Java #7

Closed ductri closed 7 years ago

ductri commented 7 years ago

I used code tag but I don't know why it doesn't show end line propriety

There are 2 bugs in code of Java. They are the same type.

double[] decisions = new double[13];
for (int i = 0, d = 0, l = 13; i < l; i++) {
    for (int j = i + 1; j < l; j++) {
        double tmp1 = 0., tmp2 = 0.;
        for (int k = starts[j]; k < ends[j]; k++) {
           tmp1 += kernels[k] * coeffs[i][k];
        }
        for (int k = starts[i]; k < ends[i]; k++) {
            tmp2 += kernels[k] * coeffs[j - 1][k];
        }
        System.out.println("d=" + d);
        decisions[d] = tmp1 + tmp2 + inters[d++];
    }
}

In my understanding, the second loop will run with d and l are always initialized to 0 and 13 correspondingly. But actually it won't. This code raise exception ArrayIndexOutOfBoundsException.

I suggest that you need to add a line: d = 0; right after the first for statement (l=13; doesn't need because it is a constant here).

The same bug with this code:

int[] votes = new int[13];
for (int i = 0, d = 0, l = 13; i < l; i++) {
    for (int j = i + 1; j < l; j++) {
        votes[d] = decisions[d++] > 0 ? i : j;
    }
}
nok commented 7 years ago

Hello @ductri,

I understand that issue, but I haven't any model which causes the described error. Can you share the original or a similar model?

Happy coding, Darius 🌵


Edit:

I found a dataset which causes the error.

nok commented 7 years ago

Hello @ductri,

the bug is fixed https://github.com/nok/sklearn-porter/commit/4ef6cad723a4c572959d67291b06ed1b7deee7e7. The size of the initialized array was too small. Thanks for your hint!

I published a minor update to pypi. Now you can update the module by typing:

pip install sklearn-porter -U

Happy coding, Darius 🌵