我正在编写一个自定义层,在该层中需要遍历批处理维,然后遍历图像的rgb维。我仍在尝试了解Tensorflow如何实现for循环,并且我不确定这与我在此处提出的错误有关。
这是一些伪代码:
@tf.function()
def _crop_and_resize(self, imgs, boxes, to_size):
# prepare kernel_h and kernel_w
n_images = tf.shape(imgs)[0]
outputs = tf.TensorArray(dtype=tf.float32, size=n_images)
for i in tf.range(n_images):
# in the call to _bilinear we enter the inner loop
output = self._bilinear(
kernel_h[i],
kernel_w[i],
imgs[i])
outputs.write(i, output)
return outputs.stack()
def _bilinear(self, kernel_h, kernel_w, img):
n_channels = tf.shape(img)[2]
result_channels = tf.TensorArray(dtype=tf.float32, size=n_channels)
for i in tf.range(n_channels):
result_channels.write(i,
tf.matmul(
tf.matmul(kernel_h, tf.tile(img[:, :, i], [1, 1])),
kernel_w, transpose_b=True))
return tf.transpose(result_channels.stack(), perm=[1,2,0])
我收到以下错误:
InvalidArgumentError:尝试仅包含未初始化的张量且具有未完全定义的element_shape的堆栈列表:[?,?,?] [[{{node model_17 / att_1 / PartitionedCall / TensorArrayV2Stack / TensorListStack}}]] [Op:__ inference_distributed_function_11150 ]函数调用堆栈:distributed_function
我已经看到了许多在单个for循环中使用TensorArray
和stack
以这种方式使用和的示例,但是我不确定嵌套的for循环是否会引起问题。
我有一个类似的问题,并通过此错误响应中的注释解决了该问题:https : //github.com/tensorflow/tensorflow/issues/30409#issuecomment-508962873
基本上,在急切模式下,.stack()调用是为了方便而就地工作,但是在图形设置中,您需要将.stack()调用链接为图形中的节点,例如
outputs = outputs.write(i, output)
这为我解决了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句