【问题标题】:Unexpected shape returned from function mapped to tensorflow dataset从映射到张量流数据集的函数返回的意外形状
【发布时间】:2021-03-20 07:36:18
【问题描述】:

我试图填充一个数据集,该数据集在第一维中包含不同长度的张量。长度是不超过 13 的任意数字,我想在第一个维度的前面填充零。当我将它应用于张量时,该函数似乎工作正常,但数据集没有像我预期的那样返回 (13,128) 的形状。我得到了 (None, None) 的形状。

代码如下:

print(train_dataset_filtered.element_spec, '\n')

def pad_seq(eng, ger):
    n = 13 - tf.shape(eng)[0]
    paddings = tf.concat(([[n,0]], [[0,0]]), axis=0)
    return tf.pad(eng, paddings), ger

print(pad_seq(tf.ones((4,128)), tf.ones((14,))), '\n')

print(train_dataset_filtered.map(pad_seq).element_spec)

输出如下:

(TensorSpec(shape=(None, 128), dtype=tf.float32, name=None), TensorSpec(shape=(14,), dtype=tf.int32, name=None)) 

(<tf.Tensor: id=402, shape=(13, 128), dtype=float32, numpy=
array([[0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       ...,
       [1., 1., 1., ..., 1., 1., 1.],
       [1., 1., 1., ..., 1., 1., 1.],
       [1., 1., 1., ..., 1., 1., 1.]], dtype=float32)>, <tf.Tensor: id=388, shape=(14,), dtype=float32, numpy=
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
      dtype=float32)>) 

(TensorSpec(shape=(None, None), dtype=tf.float32, name=None), TensorSpec(shape=(14,), dtype=tf.int32, name=None))

【问题讨论】:

    标签: tensorflow2.0 tensorflow-datasets


    【解决方案1】:

    当您使用 concat() 时,n = 13 - tf.shape(eng)[0] 的形状会导致此行为。

    在你的例子中是tf.Tensor(9, shape=(), dtype=int32)。所以最好的方法是使用stack()。更改您的代码:

    def pad_seq(eng, ger):
        n = 13 - tf.shape(eng)[0]
        paddings = tf.stack(([[n,0], [0,0]]))
        return (tf.pad(eng, paddings), ger)
    

    我还注意到您没有接受 SO 中的任何答案。请看What should I do when someone answers my question?

    【讨论】:

    • 首先,非常感谢!我实施了您的建议并得到了(无,128)的输出形状。我试图检查输出,似乎所有输出的形状都是 (13, 128) 但 element_spec 显示 (None, 128)。即使我将填充增加到某个任意大的数字,例如10000,输出形状仍然是(无,128)。你能想到为什么会这样吗?再次感谢!
    • 如果不看其余代码很难判断,但这可能是因为您映射了一个使输出为 128 维的函数。如果要检查元素的形状,则需要使用 take() 方法从数据集中获取示例。如果您想查看即 padding = 1000 的效果,您应该检查元素的形状。
    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    相关资源
    最近更新 更多