Search code examples
pythonnumpytensorflowchaquopy

Converting Arrays and Tensors in Chaquopy


How do I do this?

I saw your post saying that you can just pass java Objects to Python methods but this is not working for numpy arrays and TensorFlow tensors. The following, and various variation of this, is what I tried and to no avail.

double[][] anchors = new double[][]{{0.57273, 0.677385}, {1.87446, 2.06253}, {3.33843, 5.47434}, {7.88282, 3.52778}, {9.77052, 9.16828}};
PyObject anchors_ = numpy.callAttr("array", anchors);

I also tried to use concatenate to create this but it does not work. This is because concatenate (and stack, etc.) require a sequence containing the names of the arrays to be passed as an argument and there does not seem to be a way to do that with Chaquopy in Java.

Any advice?


Solution

  • I assume the error you received was "ValueError: only 2 non-keyword arguments accepted".

    You probably also got a warning from Android Studio in the call to numpy.array, saying "Confusing argument 'anchors', unclear if a varargs or non-varargs call is desired". This is the source of the problem. You intended to pass one double[][] argument, but unfortunately Java has interpreted it as five double[] arguments.

    Android Studio should offer you an automatic fix of casting the parameter to Object, i.e.:

    numpy.callAttr("array", (Object)anchors);
    

    This tells the Java compiler that you intend to pass only one argument, and numpy.array will then work correctly.