【问题标题】:How to filter dataset by tensor shape in Tensorflow如何在 Tensorflow 中按张量形状过滤数据集
【发布时间】:2021-05-12 13:58:12
【问题描述】:

我从 tfds.load 加载了一个数据集,并想丢弃某些干扰正确训练/对我没有用的图像(例如,太小)。

似乎在任何地方都没有关于这个特定问题的信息,所以我选择了看起来最合适的方法,即数据集上的 .filter(predicate)。不幸的是,谓词的输入具有不确定的形状 (None, None, 3),并且正如预期的那样会引发一个错误,即 'int' 无法与 'NoneType' 进行比较。

是否有可能在 tensorflow 中解决这个问题,还是我不应该浪费时间?

伪代码

ds_train = tfds.load('name')
ds_train = ds_train.map(lambda ds: ds['image'])
ds_train = ds_train.filter(lambda image: image.shape[0] >= 256)

【问题讨论】:

    标签: python tensorflow tensorflow2.0 data-processing


    【解决方案1】:

    使用tf.data.Dataset 编写代码时,应使用tf.shape(tensor) 而不是tensor.shape,因为tf.data.Dataset 在图形模式下工作。

    引用tf.shape的文档:

    tf.shape 和 Tensor.shape 在 Eager 模式下应该相同。在 tf.function 或 compat.v1 上下文中,直到执行时间才可能知道所有维度。因此,在为图形模式定义自定义层和模型时,更喜欢动态 tf.shape(x) 而不是静态 x.shape。

    ds_train = ds_train.filter(lambda image: tf.shape(image)[0] >= 256)
    

    【讨论】:

    • 没想到如此简单的解决方案可以解决它所造成的痛苦
    猜你喜欢
    • 2022-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多