张量流“地图操作”?

2024-04-29 00:58:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在调整cifar10 convolution example以适应我的问题。我想将数据输入从一个从文件中一次读取一个图像的设计更改为一个对已经存在的图像集进行操作的设计。原始的inputs()函数如下所示:

read_input = cifar10_input.read_cifar10(filename_queue)
reshaped_image = tf.cast(read_input.uint8image, tf.float32)
# Crop the central [height, width] of the image.
resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image,
                                                     width, height)

在原始版本中,read_input是包含一个图像的张量。

我把所有的图像都保存在RAM中,所以我没有使用filename_queue,而是有一个巨大的images_tensor = tf.constant(images),其中images_tensor.shape是(32,32,3)。

我的问题非常基本:对images_tensor的所有元素应用某些函数(tf.image.resize_image_with_crop_or_pad)的最佳方法是什么?

在tensorflow中,使用有限的切片(TensorFlow - numpy-like tensor indexing)迭代是有问题的。只有一个命令能解决这个问题吗?


Tags: the函数图像imagereadinputqueuetf
3条回答

Tensorflow提供了几个higher-order functions,其中一个是^{}。用法非常简单:定义映射并将其应用于张量:

variable = tf.Variable(...)
mapping = lambda x: f(x)
res = tf.map_fn(mapping, variable)

有几个答案-没有一个像map函数那么优雅。哪一个最好取决于你对记忆效率的渴望。

(a)您可以使用enqueue_many将它们放入^{}中,然后一次对图像进行出列和tf.image.resize_image_with_crop_or_pad,并将其全部压缩回一个大的smoosh中。这可能很慢。需要N个调用才能运行N个映像。

(b)您可以使用一个占位符feed并运行来调整它们的大小,然后在从原始数据源传入时对它们进行裁剪。从内存的角度来看,这可能是最好的选择,因为您永远不必将未经调整的数据存储在内存中。

(c)可以使用^{}操作遍历整个批处理,并在tf.Variable中生成结果。特别是如果利用while允许的并行执行,这可能是最快的方法。

我可能会选择(c)选项,除非你想最小化内存使用,在这种情况下,在进入(b)的路上过滤它会是一个更好的选择。

从0.8版起,存在map_fn。从documentation

map_fn(fn, elems, dtype=None, parallel_iterations=10, back_prop=True, swap_memory=False, name=None)

map on the list of tensors unpacked from elems on dimension 0.

This map operator repeatedly applies the callable fn to a sequence of elements from first to last. The elements are made of the tensors unpacked from elems. dtype is the data type of the return value of fn. Users must provide dtype if it is different from the data type of elems.

Suppose that elems is unpacked into values, a list of tensors. The shape of the result tensor is [len(values)] + fn(values[0]).shape.

Args:

fn: The callable to be performed.

elems: A tensor to be unpacked to apply fn.

dtype: (optional) The output type of fn.

parallel_iterations: (optional) The number of iterations allowed to run in parallel. back_prop: (optional) True enables back propagation. swap_memory: (optional) True enables GPU-CPU memory swapping. name: (optional) Name prefix for the returned tensors.

Returns:

A tensor that packs the results of applying fn to the list of tensors unpacked from elems, from first to last.

Raises:

TypeError: if fn is not callable.

Example:

  elems = [1, 2, 3, 4, 5, 6]
  squares = map_fn(lambda x: x * x, elems)
  # squares == [1, 4, 9, 16, 25, 36]
  ```

相关问题 更多 >