Tensorflow教程包括使用tf.expand_dims向张量添加"批量维度".我已经阅读了这个函数的文档,但它对我来说仍然是相当神秘的.有谁知道在什么情况下必须使用这个?
我的代码如下.我的意图是根据预测箱和实际箱之间的距离计算损失.(例如,如果predictedBin = 10和truthBin = 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))
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我需要申请tf.expand_dims到predictedBin和binDistanceLoss?提前致谢.
Da *_*ong 45
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.
fr_*_*lio 15
要添加Da Tong的答案,您可能希望同时扩展多个维度.例如,如果您conv1d在等级为1的向量上执行TensorFlow 操作,则需要为它们提供等级3.
执行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)
Run Code Online (Sandbox Code Playgroud)
注意:如果您收到错误TypeError: Failed to convert object of type <type 'list'> to Tensor.,请尝试传递tf.shape(x)[0]而不是此处x.get_shape()[0]建议的传递.
希望能帮助到你!
干杯,
安德烈斯
| 归档时间: |
|
| 查看次数: |
19106 次 |
| 最近记录: |