Introduction to TensorFlow Fundamentals

Introduction to TensorFlow Fundamentals

This is the first lab in the Machine Learning with TensorFlow series. The primary focus of this lab is to help you understand the fundamental components of TensorFlow.

Learning Objectives:

  • Creating scalars, vectors, matrices, and tensors
  • Inspecting different attributes of a tensor.
  • Performing basic operations on tensors.
  • Learn to index and slice tensors.
  • Reshaping and manipulating tensors.

To get the most out of this series:

  • you should know how to write code, ideally have some experience programming in Python.
  • have a decent understanding of variables, linear equations, matrices, calculus, and statistics.
  • don't just stick to the examples and code I've provided, play around and break things - that's the best way to learn.

Code/Environment Setup

In order to try out the code snippets or complete to-do tasks mentioned in each section, you can use Google Colaboratory notebook. Colab is basically Google's implementation of Jupyter Notebooks where you can run your code.

You can learn more about working with Colabs by following this notebook.

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

2