我有一个包含两个列的CSV文件:
- 图像的文件路径存储为
numpy
数组 - 图像的标签
CSV中的每一行对应于一个项目(示例(。
我想创建一个tf.data
管道,该管道读取文件路径并加载Numpy数组和与之关联的标签。我该怎么做,以便可以返回tf.data.Dataset
对象?
网站上的文档不是很有用,我无法弄清楚从哪里开始。
做到这一点的一种方法就是将这些2个文件加载到变量中并使用 tf.data.Dataset.from_tensor_slices
(请参阅https://www.tensorflow.org/guide/guide/datasets#consuming_numpy_arrays(
另一种方法是将文件路径映射到数据集中,并执行数据管道上的数据以读取并返回为(img,label(这是https://www.tensorflow.org/tutorials/load_data/images
的示例代码def load_and_preprocess_image(path):
image = tf.read_file(path)
return preprocess_image(image)
ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))
# The tuples are unpacked into the positional arguments of the mapped function
def load_and_preprocess_from_path_label(path, label):
return load_and_preprocess_image(path), label
image_label_ds = ds.map(load_and_preprocess_from_path_label)
如果数据太大而无法用于内存,我会更喜欢第二种方式,但是第一个对于小数据很方便
本教程应该是一个很好的起点:https://www.tensorflow.org/tutorials/load_data/images
如链接中所述,在图像路径及其标签中加载。使用路径及其标签的from_tensor_slices创建一个数据集,然后将带有预处理功能的路径(是字符串(映射到图像张量。
ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))
# The tuples are unpacked into the positional arguments of the mapped function
def load_and_preprocess_from_path_label(path, label):
return load_and_preprocess_image(path), label
image_label_ds = ds.map(load_and_preprocess_from_path_label)
image_label_ds
按照教程进行逐步详细信息。如果您的图像保存为Numpy数组而不是JPG文件,则必须更改一些预处理,但总体流程应该非常相似。