【问题标题】:Create tensorflow dataset of images & labels from simple python lists从简单的 python 列表创建图像和标签的 tensorflow 数据集
【发布时间】:2020-08-13 03:38:27
【问题描述】:

我一直在尝试使用各种灵感 - 特别是 this one - 创建一个带标签的图像数据集以传递给 model.fit()

我的代码看起来等同于the answer 中给出的那个问题...与问题的 OP 相比,_parse_function() 略有不同:

def load_image( path, label ):
  file_contents = tf.io.read_file( path )
  image = tf.image.decode_image( file_contents )
  image = tf.image.convert_image_dtype( image, tf.float32 )
  return image, label

我可以在 python 命令行中独立测试这个函数,例如使用image, label = load_image( "tiger.jpg", "Tiger" ) 并以"Tiger" 和正确对应图像左上角像素的image[0][0] 标签结束:

>>> image[0][0]
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([0.37254903, 0.5529412 , 0.854902  ], dtype=float32)>

同样,如果我在我的程序中尝试print( image[ 0 ][ 0 ],我会得到:

tf.Tensor([0.37254903 0.5529412  0.854902  ], shape=(3,), dtype=float32)

我是 python 新手,所以我希望这些只是一个主题的等效变体,但无论哪种方式,当我在程序中将所有内容传递给 model.fit() 时,我最终会得到:

 ValueError: Cannot take the length of shape with unknown rank.

任何主题的变化都没有让我超越这一点。我已经从数据集中消除了所有管道操作(例如,没有.shuffle(),没有.repeat(),没有.batch()),所以我只使用.map() 函数,并得到相同的错误结果。我能看到的唯一错误可能是在上面的load_image() 函数中,或者在调用代码中:

dataset = tf.data.Dataset.from_tensor_slices( ( images, labels ) )   # tf.constant() does not change error
dataset = dataset.map( load_map )
model.fit( dataset, epochs=100 )

是什么导致了错误?

【问题讨论】:

  • 您是否尝试过使用 Keras 的 Image generatorflow_from_directory 函数?它在一个小功能中做了很多事情,非常适合新手。如果您有错误,请更新您的问题....
  • 你能在图像张量上尝试set_shape吗? IE。在load_image 函数中,执行image.set_shape(image_shape)(在返回之前执行此操作,函数本身就位!!)。问题可能是 TF 不“知道”图像加载时的样子,所以你必须明确告诉它。
  • 似乎大部分问题出在load_image - 请参阅github.com/tensorflow/tensorflow/issues/14226
  • @neelg 我的图像列表是由多个带标签的文件夹组合而成的。我想通过 TF2.0+ 中的数据集了解从简单的 python 列表到 model.fit() 的程序流程。真的不应该这么晦涩难懂!
  • @omatai 正如我之前指出的,image generator 函数非常适合您。但是要使用它,您必须坚持特定的文件夹结构。您可以将汽车图像放入名为cars 的文件夹中,该功能将确定所有这些图片都是汽车并以正确的方式提供给它们。因此使用多个文件夹非常容易......

标签: python tensorflow tensorflow-datasets


【解决方案1】:

decode_image 存在一个已知问题 - 它没有正确设置形状信息(请参阅 here。您可以使用更具体的调用 - 例如 decode_jpegdecode_png

另外...您将遇到的下一个问题是您不能直接使用“Tiger”之类的标签。如果“Tiger”在 ["Lion", "Tiger", "Zebra", "Ape",...] 等类别列表中,那么您要么需要在此类列表中使用 "Tiger" 的索引(即1) 或 one-hot 表示(即[False,True,False,False,...]

【讨论】:

    【解决方案2】:

    请查看此tutorial 获取信息!

    您可以先构建 csv 文件,并将末尾列中的标签和像素作为特征。然后像这样遍历:

    titanic_csv_ds = tf.data.experimental.make_csv_dataset(
        titanic_file_path,
        batch_size=5, # Artificially small to make examples easier to show.
        label_name='survived',
        num_epochs=1,
        ignore_errors=True,)
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2020-07-22
      • 2017-11-14
      • 1970-01-01
      • 2020-09-23
      • 2020-12-08
      • 1970-01-01
      • 2019-07-02
      • 2021-12-11
      相关资源
      最近更新 更多