Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using tf.expand_dims and tf.newaxis in Tensorflow?

Hi I am new to Tensorflow.
I want to change the dimention of Tensor, and I found 3 types of method to implement this, like below:

a = tf.constant([[1,2,3],[4,5,6]]) # shape (2,3)

# change dimention of a to (2,3,1)
b = tf.expand_dims(a,2)   # shape(2,3,1)
c = a[:,:,tf.newaxis]     # shape(2,3,1)
d = tf.reshape(a,(2,3,1)) # shape(2,3,1)

Is there any difference among the 3 methods, e.g. in terms of performance?
Which method should I use?

like image 743
Yohei Avatar asked Aug 09 '18 01:08

Yohei


People also ask

What is TF Expand_dims for?

expand_dims() TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. expand_dims() is used to insert an addition dimension in input Tensor.

What is TF stack?

tf.stack( values, axis=0, name='stack' ) Defined in tensorflow/python/ops/array_ops.py. Stacks a list of rank- R tensors into one rank- (R+1) Packs the list of tensors in values into a tensor with rank one higher than each tensor in values , by packing them along the dimension.

What is TF Where?

tf. where will return the indices of condition that are non-zero, in the form of a 2-D tensor with shape [n, d] , where n is the number of non-zero elements in condition ( tf. count_nonzero(condition) ), and d is the number of axes of condition ( tf. rank(condition) ). Indices are output in row-major order.


1 Answers

There is no real difference between the three, but sometimes one or the other may be more convenient:

  • tf.expand_dims(a, 2): Convenient when you want to add one dimension and its index is variable (for example the result of another TensorFlow operation, or some function parameter). Depending on your style you may find it more readable, since it clearly expresses the intention of adding a dimension.
  • a[:,:,tf.newaxis]: Personally I use this a lot because I find it readable (maybe because I'm used to it from NumPy), although not in every case. Especially convenient if you want to add multiple dimensions (instead of calling tf.expand_dims multiple times). Also (obviously) if you want to take a slice and add new dimensions at the same time. However it is not usable with variable axis indices, and if you have many dimensions tf.expand_dims may be less confusing.
  • tf.reshape(a,(2,3,1)): Personally I rarely or never use this to just add a dimension, because it requires me to know and specify all (or all but one) the remaining dimension sizes, and also it may be misleading when reading the code. However, if I need to reshape and add a dimension, I usually do it in the same operation.
like image 155
jdehesa Avatar answered Sep 29 '22 20:09

jdehesa