简体   繁体   English

将可变大小的 numpy 数组转换为 Tensorflow 张量

[英]Convert a variable sized numpy array to Tensorflow Tensors

I am trying Tensorflow 2.0 alpha preview and was testing the Eager execution.我正在尝试 Tensorflow 2.0 alpha 预览并正在测试 Eager 执行。 My doubt is that if you have a numpy array of variable size in middle like我的疑问是,如果你在中间有一个可变大小的 numpy 数组

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.以此类推数组的rest,如何急切地将它们转换为张量。

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.). ValueError:无法将 numpy ndarray 转换为 Tensor(无法将元素作为字节获取。)。

Converting each sub-array works, but because the sub-array size isn't same, tf.stack doesn't work.转换每个子数组都可以,但是因为子数组大小不一样,所以 tf.stack 不起作用。

Any help or suggestions?有什么帮助或建议吗?

This was happening to me in eager as well.这也发生在我身上。 Looking at thedocs here , I ended up trying看看这里文档,我最终尝试

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

And that worked for me.这对我有用。

If you can make lists of arrays, then tf.ragged.stack should do it.如果您可以列出 arrays,那么tf.ragged.stack应该可以做到。 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 .这会将不均匀大小的 arrays 堆叠到RaggedTensor中。

It seems that the only way to work with this is to use lists of lists and then convert them to ragged tensors, since numpy doesnt support ragged arrays very well.似乎唯一的方法是使用列表列表,然后将它们转换为参差不齐的张量,因为 numpy 不能很好地支持参差不齐的数组。 Will Update if I find anything new如果我发现任何新东西会更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM