gpt4 book ai didi

python - 使用数据集 API 在 Tensorflow 中滑动批处理窗口

转载 作者:太空狗 更新时间:2023-10-29 22:20:47 25 4
gpt4 key购买 nike

有没有办法在批处理中修改我的图像的构图?目前,当我正在创建例如大小为 4 的批处理,我的批处理将如下所示:

第 1 批:[Img0 Img1 Img2 Img3]第 2 批:[Img4 Img5 Img6 Img7]

我需要修改我的批处理的组成,以便它只转移一次到下一张图像。那么它应该是这样的:

第 1 批:[Img0 Img1 Img2 Img3]第 2 批:[Img1 Img2 Img3 Img4]第 3 批:[Img2 Img3 Img4 Img5]第 4 批:[Img3 Img4 Img5 Img6]第 5 批:[Img4 Img5 Img6 Img7]

我在我的代码中使用了 Tensorflow 的数据集 API,如下所示:

def tfrecords_train_input(input_dir, examples, epochs, nsensors, past, future,
features, batch_size, threads, shuffle, record_type):
filenames = sorted(
[os.path.join(input_dir, f) for f in os.listdir(input_dir)])
num_records = 0
for fn in filenames:
for _ in tf.python_io.tf_record_iterator(fn):
num_records += 1
print("Number of files to use:", len(filenames), "/ Total records to use:", num_records)
dataset = tf.data.TFRecordDataset(filenames)
# Parse records
read_proto = partial(record_type().read_proto, nsensors=nsensors, past=past,
future=future, features=features)
# Parallelize Data Transformation on available GPU
dataset = dataset.map(map_func=read_proto, num_parallel_calls=threads)
# Cache data
dataset = dataset.cache()
# repeat after shuffling
dataset = dataset.repeat(epochs)
# Batch data
dataset = dataset.batch(batch_size)
# Efficient Pipelining
dataset = dataset.prefetch(2)
iterator = dataset.make_one_shot_iterator()
return iterator

最佳答案

可以使用滑动窗口tf.data.Dataset进行批量操作:

示例:

from tensorflow.contrib.data.python.ops import sliding

imgs = tf.constant(['img0','img1', 'img2','img3', 'img4','img5', 'img6', 'img7'])
labels = tf.constant([0, 0, 0, 1, 1, 1, 0, 0])

# create TensorFlow Dataset object
data = tf.data.Dataset.from_tensor_slices((imgs, labels))

# sliding window batch
window = 4
stride = 1
data = data.apply(sliding.sliding_window_batch(window, stride))

# create TensorFlow Iterator object
iterator = tf.data.Iterator.from_structure(data.output_types,data.output_shapes)
next_element = iterator.get_next()

# create initialization ops
init_op = iterator.make_initializer(data)

with tf.Session() as sess:
# initialize the iterator on the data
sess.run(init_op)
while True:
try:
elem = sess.run(next_element)
print(elem)
except tf.errors.OutOfRangeError:
print("End of dataset.")
break

输出:

 (array([b'img0', b'img1', b'img2', b'img3'], dtype=object), array([0, 0, 0, 1], dtype=int32))
(array([b'img1', b'img2', b'img3', b'img4'], dtype=object), array([0, 0, 1, 1], dtype=int32))
(array([b'img2', b'img3', b'img4', b'img5'], dtype=object), array([0, 1, 1, 1], dtype=int32))
(array([b'img3', b'img4', b'img5', b'img6'], dtype=object), array([1, 1, 1, 0], dtype=int32))
(array([b'img4', b'img5', b'img6', b'img7'], dtype=object), array([1, 1, 0, 0], dtype=int32))

关于python - 使用数据集 API 在 Tensorflow 中滑动批处理窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50612215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com