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

2024-04-20 14:45:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个现有的复杂模型。里面有张量x和形状(None,128,128,3)。第一个轴具有动态形状,当批处理传递到session.run中的feed_dict时,应该将其具体化。但是,当我尝试将广播操作定义为x的形状时:

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

出现异常:

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.

异常发生在创建模型时,而不是运行模型时。将第一个元素转换为数字有帮助,但这不是解决方案。你知道吗


Tags: torun模型none定义sessiontffeed
1条回答
网友
1楼 · 发布于 2024-04-20 14:45:54

.shape属性提供了图形构造时已知的形状,这是一个^{}结构。如果x的形状是完全已知的,那么可以让代码按如下方式工作:

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

然而,在您的例子中x有一个未知的第一维度。为了将实际的张量形状用作规则的^{}(只有在运行时才知道值),可以使用^{}

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

相关问题 更多 >