如果您有tfrecords
文件:
path = ['file1.tfrecords', 'file2.tfrecords', ..., 'fileN.tfrecords']
dataset = tf.data.Dataset.list_files(path, shuffle=True).repeat()
dataset = dataset.interleave(lambda filename: tf.data.TFRecordDataset(filename), cycle_length=len(path))
dataset = dataset.map(parse_function).batch()
parse_function 处理解码和任何类型的扩充。
如果使用 numpy 数组,您可以从文件名列表或数组列表中构造数据集。标签只是一个列表。或者它们可以在解析单个示例时从文件中获取。
path = #list of numpy arrays
或者
path = os.listdir(path_to files)
dataset = tf.data.Dataset.from_tensor_slices((path, labels))
dataset = dataset.map(parse_function).batch()
parse_function 处理解码:
def parse_function(filename, label): #Both filename and label will be passed if you provided both to from_tensor_slices
f = tf.read_file(filename)
image = tf.image.decode_image(f))
image = tf.reshape(image, [H, W, C])
label = label #or it could be extracted from, for example, filename, or from file itself
#do any augmentations here
return image, label
要解码 .npy 文件,最好的方法是不使用reshape
or read_file
,decode_raw
但首先使用 numpys 加载np.load
:
paths = [np.load(i) for i in ["x1.npy", "x2.npy"]]
image = tf.reshape(filename, [2])
或尝试使用decode_raw
f = tf.io.read_file(filename)
image = tf.io.decode_raw(f, tf.float32)
然后只需将批处理数据集传递给model.fit(dataset)
. TensorFlow 2.0 允许对数据集进行简单的迭代。无需使用迭代器。即使在更高版本的 1.x API 中,您也可以将数据集传递给.fit
方法
for example in dataset:
func(example)