简体   繁体   English

为什么 tensorflow 可能想要指定动态维度

[英]Why tensorflow may want to specify dynamic dimension

I have an existing complex model.我有一个现有的复杂模型。 Inside there is tensor x with shape (None, 128, 128, 3).里面有形状为 (None, 128, 128, 3) 的张量x First axis has dynamic shape, that should be materialized when batch is passed to feed_dict in session.run .第一个轴具有动态形状,应在将批处理传递给session.run feed_dict时实现。 However when I attempt to define broadcast operation to shape of x:但是,当我尝试将广播操作定义为 x 的形状时:

y = tf.broadcast_to(z, (x.shape[0], x.shape[1], x.shape[2], 1))

Exception is raised:引发异常:

Failed to convert object of type <class 'tuple'> to 
Tensor. Contents: (Dimension(None), Dimension(128), 
Dimension(128), 1). Consider casting elements to a supported type.

Exception occurs when creating model, not when running it.创建模型时发生异常,而不是运行它时。 Converting first element to number helps, but this is not the solution.将第一个元素转换为数字有帮助,但这不是解决方案。

The .shape attribute gives you the shape known at graph construction time, which is atf.TensorShape structure. .shape属性为您提供图形构建时已知的形状,这是一个tf.TensorShape结构。 If the shape of x were fully known, you could get your code to work as follows:如果x的形状是完全已知的,你可以让你的代码如下工作:

y = tf.broadcast_to(z, (x.shape[0].value, x.shape[1].value, x.shape[2].value, 1))

However, in your case x has an unknown first dimension.但是,在您的情况下, x具有未知的第一维。 In order to use the actual tensor shape as a regular tf.Tensor (with value only known at runtime), you can use tf.shape :为了将实际张量形状用作常规tf.Tensor (仅在运行时已知值),您可以使用tf.shape

x_shape = tf.shape(x)
y = tf.broadcast_to(z, (x_shape[0], x_shape[1], x_shape[2], 1))

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

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