【发布时间】: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 generator和flow_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