Indexing and slicing across multiple axes

Indexing and slicing are two very important techniques to manipulate tensors and arrays of data and works similar to what we see in python lists or np.arrays.

We follow the standard Python indexing rules.

  • indexes start at 0
  • negative indices count backwards from the end
  • colons, :, are used for slices: start:stop:step

Let's create a new tensor.

##creating tensor using Variable class
t1 = tf.Variable([2.0, 3.5, 0.9, 4.5, 5, 9, 10])
t1

Check out the 4th element of tensor t1

##checking 4th element of t1
t1[3]

Indexing starts from zero here as well. This gives you a tensor object. If you want to extract the value at that index:

##getting 4th element from the tensor.
t1[3].numpy()

For a 2D tensor:

b = tf.Variable([[5,6],
                 [7,8]] )  # a variable tensor  
print(b)

To access 6 from this 2D tensor, you'll have to mention its index on the first axis and then its index on the second axis:

##accessing 6 from b
b[0,1]

Try to access other elements.

Slicing for subsetting data

Slicing also works the same way:

##checking out slicing
print(f"First element of the tensor: {t1[0]}")
print(f"Last element of the tensor: {t1[-1]}")
print(f"Elements after index 3: {t1[4:]}")
print(f"Elements before index 4: {t1[:4]}")
print(f"Elements between index 2 and 5:  {t1[3:5]}")

Run it, play around with it and check the output for yourself!

Output:

Next Steps!

Indexing and slicing are important especially when it comes to splitting datasets and congratulations, now you know how to do that.

While training neural networks for computer vision applications, you frequently stumble upon datasets that need to be reshaped and that's something you should prepare yourself to handle. 

So, let's learn to reshape tensors now.

Discussion
Excellent tutorial for beginners. Waiting for the next lab on training your first neural network.

5

1