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.
- 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.
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.
Create basic tensors using tf.constant()
Let's create a scalar first:
r0_tensor = tf.constant(4) r0_tensor
Running the cell would give you the following:
<tf.Tensor: shape=(), dtype=int32, numpy=4>
tf.constant() creates a constant tensor in the form of a tensor-like object that has:
shape - the number of elements in each of the axes of a tensor.
dtype - the data type of the elements in the tensor.
numpy - every tensor has a numpy method that lets you access the value from the tensor object.
Create a Vector
Try to create a vector now which is a 1D array passed to the tf.constant().
r1_tensor = tf.constant([3, 5.0, 6]) r1_tensor
Try it: What did you get in the output this time? Did you notice something unique?
Create a Matrix / Rank-2 Tensor
r2_tensor = tf.constant([[2,3], [4,5], [6,7]]) r2_tensor
<tf.Tensor: shape=(3, 2), dtype=int32, numpy= array([[2, 3], [4, 5], [6, 7]], dtype=int32)>
Create a Rank-3 Tensor
r3_tensor = tf.constant([ [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], [[10, 11, 12, 13, 14], [15, 16, 17, 18, 19]], [[20, 21, 22, 23, 24], [25, 26, 27, 28, 29]],]) print(r3_tensor)
Let's look at the output of these now:
Try answering the following questions after running the code above:
- What is the shape of the tensor?
- What is the data type of the elements in the tensor?
- How many axes does this tensor have?
- What is the total number of elements in the tensor?
Also, try creating a rank-4 tensor yourself, you might want to try looking at tf.zeros for an easy way out.
Use this momentum, keep going!
So, you have learned what scalars, vectors and matrices are and how you can create these using tensorflow. The next steps should be to understand the attributes and what we can do with them.
Let's dive right in!