【问题标题】:filter dataset by label in tensorflow在张量流中按标签过滤数据集
【发布时间】:2022-08-27 22:27:59
【问题描述】:

我是 tensorflow(和一般的 python)的新手,我很难理解张量的这些特性。我正在使用tf.keras.utils.image_dataset_from_directory() 来获取图像和标签(类)的数据集。我想使用 filter() 按类过滤 imgaes。就像是,

full_ds = tf.keras.utils.image_dataset_from_directory(
    'the_path',
    image_size=(SIZE,SIZE),
)
fibrosis_ds = full_ds.filter(lambda x, y:  y==0 ) # y == 0 for fibrosis

这给出了错误

值错误:predicate 无效。 predicate 必须返回一个 tf.bool 标量张量,但它的返回类型是 NoneTensorSpec()。

如果我在 lambda 中打印 y ,则输出为

张量("args_1:0", shape=(None,), dtype=int32)

如果我循环打印

for x, y in full_ds:
    print(y)
    break

输出是

tf.Tensor([1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1], shape=(32,), dtype=int32)

这是有道理的,因为 image_dataset_from_directory() 的默认值为 32。此数组中的 0 代表纤维化,而 1 是不同的分类(法线)。

如何让 lambda 与 filter() 一起使用。

【问题讨论】:

    标签: python tensorflow filter tensorflow-datasets


    【解决方案1】:

    问题似乎是批量执行过滤器。取消批处理并使用tf.data.Dataset.filter

    fibrosis_ds = full_ds.unbatch().filter(lambda x, y:  tf.equal(y, 0) ).batch(32) # y == 0 for fibrosis
    

    或者只使用tf.data.Dataset.map(最好):

    fibrosis_ds = full_ds.map(lambda x, y:  (x[y==0], y[y==0]))
    # or
    fibrosis_ds = full_ds.map(lambda x, y:  (tf.boolean_mask(x, y==0), tf.boolean_mask(y, y==0)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2019-12-25
      • 2019-03-28
      • 1970-01-01
      • 2012-11-28
      • 2017-08-16
      相关资源
      最近更新 更多