gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:07:59 24 4
gpt4 key购买 nike

我有一个现有的复杂模型。里面有一个张量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.

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

最佳答案

.shape 属性为您提供图形构建时已知的形状,即 tf.TensorShape结构。如果 x 的形状完全已知,您可以让代码按如下方式工作:

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

但是,在您的情况下,x 的第一维未知。为了使用实际的张量形状作为常规tf.Tensor (只有在运行时才知道值),您可以使用 tf.shape :

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

关于python - 为什么 tensorflow 可能想要指定动态维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55145714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com