2016-08-18 4 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)) 

, 나는 predictedBinbinDistanceLosstf.expand_dims을 적용해야합니까? 미리 감사드립니다.

답변

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 연산을 수행하는 경우 순위 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) 

참고 : 오류 TypeError: Failed to convert object of type <type 'list'> to Tensor.를 얻을 수 경우, here을 제안 tf.shape(x)[0]을 통과하는 대신 x.get_shape()[0]하려고합니다.

희망이 있습니다.
건배,
안드레스

+0

는 하나의'reshape'을하는 것은, 말하자면, 두 개 또는 세 개의'expand_dims'하고보다 빠른 여부를 확인하기 위해 어떤 테스트를 실행 있나요? – Nathan

+0

정말 아닙니다! 나는 [출처] (https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/array_ops.py)를 살펴 봤지만 gen_array_ops가 어디에 있는지 이해할 수 없었으므로 많이 말하면 ... 몇 가지 검사를 보는 데 확실히 관심이 있습니다. –