Tensorflow 2.0 stack()引发未初始化张量错误



我正在编写一个自定义层,其中我需要循环通过批处理维度,然后是图像的rgb维度。我仍在努力理解Tensorflow是如何实现循环的,我不确定这是否与我在这里提出的错误有关。

这里有一些伪代码:

@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:[?,?,?]的列表[[{节点模型_17/att_1/PartitionedCall/TensorArrayV2Stack/TensorListStack}}]][操作:__explorence_distributed_function_11150]函数调用堆栈:分布式功能

我见过许多以这种方式将TensorArraystack用于单个for循环的例子,但我不确定嵌套的for循环是否会导致问题。

我遇到了一个类似的问题,并从这个错误响应中的注释中解决了它:https://github.com/tensorflow/tensorflow/issues/30409#issuecomment-508962873

基本上,当处于急切模式时,.stack((调用可以方便地工作,但在图形设置中,您需要将.stack(调用链接为图形中的节点,例如

outputs = outputs.write(i, output)

这为我解决了问题。

最新更新