【问题标题】:tf.vectorized_map does not concat variable length tensors (InvalidArgumentError: PartialTensorShape: Incompatible shapes during merge)tf.vectorized_map 不连接可变长度张量(InvalidArgumentError:PartialTensorShape:合并期间不兼容的形状)
【发布时间】:2022-01-27 09:04:16
【问题描述】:

当我尝试 tf.concat 两个形状依赖于矢量化函数中的函数输入的张量时,我遇到了“InvalidArgumentError:PartialTensorShape:合并期间不兼容的形状”错误(即使输出形状对于每个 a,b 对)。下面是一个例子

import tensorflow as tf 

def test_fn(inputs):
    a,b = inputs
    out = tf.concat([tf.ones(a),tf.zeros(b)],0)
    return out

a = tf.constant([5,4,3,2])
b = tf.constant([5,6,7,8])
x_a = tf.vectorized_map(test_fn,(a,b))

我正在寻找错误发生原因的解释。

注意:我注意到源代码中的注释“-fn 的计算中任何中间或输出张量的形状和 dtype 不应依赖于 fn 的输入。”这似乎是这里的场景。是否有仍然可以利用矢量化的解决方法?

使用x_a = tf.map_fn(test_fn,(a,b),fn_output_signature=tf.TensorSpec((10,))) 有效,但不能并行化。

【问题讨论】:

    标签: python tensorflow vectorization tensorflow2.0 tensor


    【解决方案1】:

    问题是您将张量传递给 tf.onestf.zeros 而不是形状。例如,如果您将张量 a 传递给 tf.ones,它将被解释为导致形状为 (5, 4, 3, 2) 的张量的形状。那可能不是你想要的。试试这样的:

    import tensorflow as tf 
    
    def test_fn(inputs):
      a, b = inputs
      out = tf.stack([tf.ones_like(a), tf.zeros_like(b)], 0)
      return out
    
    a = tf.constant([5,4,3,2])
    b = tf.constant([5,6,7,8])
    x_a = tf.vectorized_map(test_fn,(a,b))
    x_a = tf.transpose(x_a)
    print(x_a)
    
    tf.Tensor(
    [[1 1 1 1]
     [0 0 0 0]], shape=(2, 4), dtype=int32)
    

    请注意,您必须使用 tf.stack 而不是 tf.concat,因为 TF 目前在使用 tf.vectorized_map 时不支持标量连接。在此处查看tf.vectorized_maplimitations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-12
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多