2016-08-18 98 views
7

Tensorflow教程包括使用tf.expand_dims将“批量维”添加到张量中。我已经阅读了这个功能的文档,但它对我仍然很神秘。有谁知道在什么情况下必须使用?Tensorflow:何时使用tf.expand_dims?

我的代码如下。我的意图是根据预测箱和实际箱之间的距离来计算损失。 (例如,如果predictedBin = 10truthBin = 7,则binDistanceLoss = 3)。

batch_size = tf.size(truthValues_placeholder) 
labels = tf.expand_dims(truthValues_placeholder, 1) 
predictedBin = tf.argmax(logits) 
binDistanceLoss = tf.abs(tf.sub(labels, logits)) 

在这种情况下,我需要申请tf.expand_dimspredictedBinbinDistanceLoss?提前致谢。

回答

16

expand_dims将不添加或减少张量中的元素,它只是通过将1添加到尺寸来更改形状。例如,具有10个元素的矢量可以被视为10x1矩阵。

我遇到的情况使用expand_dims是当我试图建立一个ConvNet分类灰度图像。灰度图像将作为大小为[320, 320]的矩阵加载。但是,tf.nn.conv2d需要输入为[batch, in_height, in_width, in_channels],其中in_channels维度在我的数据中丢失,在这种情况下应为1。所以我用expand_dims来增加一个维度。

就你而言,我认为你不需要expand_dims

6

要添加到Da Tong的答案,您可能需要同时扩展多个维度。例如,如果您正在对等级1的向量执行TensorFlow的conv1d操作,则需要为它们提供等级三。

执行expand_dims几次是可读的,但可能会在计算图中引入一些开销。你可以用reshape得到一个班轮相同的功能:

import tensorflow as tf 

# having some tensor of rank 1, it could be an audio signal, a word vector... 
tensor = tf.ones(100) 
print(tensor.get_shape()) # => (100,) 

# expand its dimensionality to fit into conv2d 
tensor_expand = tf.expand_dims(tensor, 0) 
tensor_expand = tf.expand_dims(tensor_expand, 0) 
tensor_expand = tf.expand_dims(tensor_expand, -1) 
print(tensor_expand.get_shape()) # => (1, 1, 100, 1) 

# do the same in one line with reshape 
tensor_reshape = tf.reshape(tensor, [1, 1, tensor.get_shape().as_list()[0],1]) 
print(tensor_reshape.get_shape()) # => (1, 1, 100, 1) 

注:如果你得到的错误TypeError: Failed to convert object of type <type 'list'> to Tensor.,试图通过tf.shape(x)[0]而不是x.get_shape()[0]的建议here

希望它有帮助!
干杯,
安德烈斯

+0

你有没有运行任何测试,看看是否在做一个'reshape'是不是做,比如说,两个或三个'expand_dims'更快? – Nathan

+0

不是真的!我查看了[sources](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/array_ops.py),但无法理解gen_array_ops的位置,所以我可以说得不好......会对看到一些测试感兴趣 –