Search code examples
pythontensorflowtensordimensions

Difference between tensor axis -1 , 1 and 0 while expanding


Below is my tensor data, not able to understand difference between axis -1 and 1 both are giving same result. Also when axis is 0 it is giving me more than 10 records.

X_regr_train, X_regr_train.shape  

(array([  0,  10,  20,  30,  40,  50,  60,  70,  80,  90, 100, 110, 120,
    130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250,
    260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380,
    390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510,
    520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640,
    650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770,
    780, 790]), (80,))

X_regr_train_exp = tf.expand_dims(X_regr_train, axis=-1)
X_regr_train_exp[:10], X_regr_train_exp.shape 

(<tf.Tensor: shape=(10, 1), dtype=int64, numpy=
 array([[ 0],
    [10],
    [20],
    [30],
    [40],
    [50],
    [60],
    [70],
    [80],
    [90]])>, TensorShape([80, 1]))


X_regr_train_exp = tf.expand_dims(X_regr_train, axis=0)
X_regr_train_exp[:10], X_regr_train_exp.shape  

(<tf.Tensor: shape=(1, 80), dtype=int64, numpy=
 array([[  0,  10,  20,  30,  40,  50,  60,  70,  80,  90, 100, 110, 120,
     130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250,
     260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380,
     390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510,
     520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640,
     650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770,
     780, 790]])>, TensorShape([1, 80]))

X_regr_train_exp = tf.expand_dims(X_regr_train, axis=1)
X_regr_train_exp[:10], X_regr_train_exp.shape  


(<tf.Tensor: shape=(10, 1), dtype=int64, numpy=
 array([[ 0],
    [10],
    [20],
    [30],
    [40],
    [50],
    [60],
    [70],
    [80],
    [90]])>, TensorShape([80, 1]))

What is the easiest way to understand these tensor axis so that it is easy to reshape while working in deep learning.


Solution

  • axis=-1 means the last axis. So in your case, axis=1 and axis=-1 is the same axis.

    After the command

    X_regr_train_exp = tf.expand_dims(X_regr_train, axis=0)
    

    the shape of the tensor is (1, 80), in the first dimension you have 1, so X_regr_train_exp[:10] will output you only 1 item, of length 80.