(Java) Tensor.fromBlob(data, shape) how to define shape for 2D and more?

Hi,
I have a more java related question but I’m stuck. In the examples on Android, we can read:

Tensor input = Tensor.fromBlob(data, new long[]{1, data.length});

In my case, I have an array:

float[][] myArray = new float[150][7];

And

Tensor input = Tensor.fromBlob(myArray, new long[]{1, myArray.length});

Doesn’t work.

Ok I got it. Didn’t read properly the doc. I need to flatten my array and then give the proper tensor dimension.

Can you give a link to the documentation page that shows how to flatten the array? (I have the same problem)

@Venryx You have to do it yourself. If you use Kotlin, you have a method https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/flatten.html
If you use Java, you can do it recursively (https://stackoverflow.com/questions/31851548/flatten-nested-arrays-in-java might help, I didn’t check the content).

In my case, my model is expecting an array of float of dimension (n, b, m). So in kotlin:

...
val input: Tensor = Tensor.fromBlob(myFloatArray, longArrayOf(n, b, m))
val output: Tensor = module.forward(IValue.from(input))!!.toTensor() 
...

You can find the doc there: https://pytorch.org/docs/1.3.0/org/pytorch/Tensor.html#id2
Hope it helps.

1 Like