Search code examples
javatensorflowincompatibletypeerror

Java incompatible type error


The following code is a part of a java program for making predictions with inception v3 model using Tensorflow library.

private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) {
    try (Graph g = new Graph()) {
        g.importGraphDef(graphDef);
        try (Session s = new Session(g);
                Tensor result = s.runner().feed("DecodeJpeg/contents", image).fetch("softmax").run().get(0)) {
            final long[] rshape = result.shape();
            if (result.numDimensions() != 2 || rshape[0] != 1)
            {
                throw new RuntimeException(
                        String.format(
                                "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
                                Arrays.toString(rshape)));
            }
            int nlabels = (int) rshape[1];

            return result.copyTo(new float[1][nlabels])[0];
        }
    }
}

The return statement however shows the error:

incompatable types, required:float,found:Object.

I tried type casting to float[] but that gave me a run time error "Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [[F cannot be cast to [F".

I downloaded the program from https://github.com/emara-geek/object-recognition-tensorflow

Im using IntelliJ IDE. What should I change?


Solution

  • Okay I figured it out.Replace the following

    result.copyTo(new float[1][nlabels])[0];
    

    to the following:

                float[][] res = new float[1][nlabels];
    
                result.copyTo(res);
    
                return res[0];
    

    Perhaps the first line of code works with the version being used by the code author but I cant be certain. The second set of code worked on java vesion 7.