Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a variable sized numpy array to Tensorflow Tensors

I am trying Tensorflow 2.0 alpha preview and was testing the Eager execution . My doubt is that if you have a numpy array of variable size in middle like

input.shape
(10,)

input[0].shape
(109, 16)

input[1].shape
(266, 16)

and so on for the rest of the array , how does one eagerly convert them to tensors.

when I try

tf.convert_to_tensor(input)

or

tf.Variable(input)

I get

ValueError: Failed to convert numpy ndarray to a Tensor (Unable to get element as bytes.).

Converting each sub-array works , but because the sub-array size isn't same , tf.stack doesn't work.

Any help or suggestions ?

like image 887
Niteya Shah Avatar asked Oct 17 '22 05:10

Niteya Shah


2 Answers

This was happening to me in eager as well. Looking at the docs here , I ended up trying

tf.convert_to_tensor(input, dtype=tf.float32)

And that worked for me.

like image 138
HeyWatchThis Avatar answered Oct 21 '22 08:10

HeyWatchThis


If you can make lists of arrays, then tf.ragged.stack should do it. You can use it like this for example:

tf.ragged.stack([tf.convert_to_tensor(arr) for arr in arrays], axis=0)

This will stack uneven sized arrays into a RaggedTensor.

like image 35
Phoenix Avatar answered Oct 21 '22 07:10

Phoenix