Converting Arrays and Tensors in Chaquopy

白昼怎懂夜的黑 提交于 2019-12-24 06:34:18

问题


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?


回答1:


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.




回答2:


I have managed to find two ways that actually work in converting this toy array into proper Python arrays.

  • In Java:
import com.chaquo.python.*;

Python py = Python.getInstance();
PyObject np = py.getModule("numpy");
PyObject anchors_final = np.callAttr("array", anchors[0]);
anchors_final = np.callAttr("expand_dims", anchors_final, 0);
for (int i=1; i < anchors.length; i++){
  PyObject temp_arr = np.callAttr("expand_dims", anchors[i], 0);
  anchors_final = np.callAttr("append", anchors_final, temp_arr, 0);
}
// Then you can pass it to your Python file to do whatever


  • In Python (the simpler way)

After passing the array to your Python function, using for example:

import com.chaquo.python.*;

Python py = Python.getInstance();
PyObject pp = py.getModule("file_name");
PyObject output = pp.callAttr("fnc_head", anchors);

In your Python file, you can simply do:

def fnc_head():
    anchors = [list(x) for x in anchors]
    ...
    return result

These were tested with 2-d arrays. Other array types would likely require modifications.



来源:https://stackoverflow.com/questions/56651034/converting-arrays-and-tensors-in-chaquopy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!