Table of contents
1.
Introduction
2.
Tensors
3.
TensorFlow
4.
What is Tensor Slicing?
5.
Performing Tensor Slicing using Tensorflow
6.
Frequently Asked Questions
6.1.
What is a tensor?
6.2.
What is the difference between a tensor and a matrix?
6.3.
What are the common libraries used for machine learning?
6.4.
Why is TensorFlow faster than PyTorch?
6.5.
What is PyTorch?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Tensorflow Advanced: Tensor Slicing

Author Shubham Das
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

While working on machine learning and deep learning, it becomes necessary to work with tensors. In this article, we will discuss a concept related to tensors which is Tensor Slicing.

Tensorflow Advanced Tensor Slicing

But we need to understand what tensors are before diving into the concepts.

Tensors

A tensor is an algebraic object that describes a multilinear relationship between sets of algebraic objects related to a vector space. Tensors may map between objects, such as vectors, scalars, and even other tensors. We can implement various operations to tensors. After understanding the tensors, let's have a basic introduction to TensorFlow.

TensorFlow

tensorflow

TensorFlow is a free library mainly used for artificial intelligence and machine learning. It is developed by Google. TensorFlow enables fast numerical computing. By using TensorFlow, we can implement model tracking, performance monitoring, data automation, and model retraining.

What is Tensor Slicing?

Tensor slicing refers to selecting elements of the tensor by using the slicing operator, which is denoted by the symbol ':' (colon). We can also slice tensors by using tf.slice.

Performing Tensor Slicing using Tensorflow

Before using a tensor, we need to import some libraries.

Code

import tensorflow as tf # Importing TensorFlow library
import numpy as np # Importing NumPy library
You can also try this code with Online Python Compiler
Run Code

Hurray! We have imported the necessary libraries.

 

Now, let's create a 1-D tensor and print it.

Code

t1 = tf.constant([1,3,5,7,2,4,6,8])
print(t1)
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor([1 3 5 7 2 4 6 8], shape=(8,), dtype=int32)

 

Now, let's slice this 1-D tensor using tf.slice.
Code

print(tf.slice(t1, begin=[3], size=[4]))
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor([7 2 4 6], shape=(4,), dtype=int32)

 

Now let's slice the 1-D tensor using tf.slice.

Code

print(t1[3:6])
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor([7 2 4], shape=(3,), dtype=int32)

 

Code

print(t1[-4:])


Output

tf.Tensor([2 4 6 8], shape=(4,), dtype=int32)

 

Now let's create a 2-D tensor and print it.

Code

t2 = tf.constant([[2, 4, 6, 8, 0],
                 [1, 3, 5, 7, 9],
                 [10, 11, 12, 13, 14],
                 [15, 16, 17, 18, 19]])
print(t2)
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor(
[[ 2  4  6  8  0]
[ 1  3  5  7  9]
[10 11 12 13 14]
[15 16 17 18 19]], shape=(4, 5), dtype=int32)

 

Now let's try to slice the 2-D tensor.

Code

print(t2[:-2, 2:4])
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor(
[[6 8]
[5 7]], shape=(2, 2), dtype=int32)

 

We can use tf.slice on higher dimensional tensors as well.

Code

t3 = tf.constant([[[2, 3, 5, 7],
                 [11, 13, 17, 19]],
                 [[17, 19, 23, 29],
                 [25, 27, 29, 31]]
                 ])
print(tf.slice(t3,
             begin=[1, 1, 0],
             size=[1, 1, 2]))
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor([[[25 27]]], shape=(1, 1, 2), dtype=int32)

 

We can also use tf.gather to get articular indices from a single axis of a tensor.

Code

print(tf.gather(t1, indices=[0, 3, 6]))
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor([1 7 6], shape=(3,), dtype=int32)

You can notice that it is the same output if we do t1[::3].

 

To extract slices from multiple axes of a tensor, we can use tf.gather_nd. We can use this when we want to gather the elements of the matrix as opposed to just its rows or columns.

Code

t4 = tf.constant([[0, 1],
                 [2, 3],
                 [4, 5],
                 [6, 7],
                 [8, 9]])
print(tf.gather_nd(t4,
                 indices=[[0], [4], [2]]))
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor(
[[0 1]
[8 9]
[4 5]], shape=(3, 2), dtype=int32)

 

We can also insert data into tensors with the help of tf.scatter_nd to insert values at the required indices, which start from zero.

Code

t6 = tf.constant([10]) # Creating a tensor with values zero in it
indices = tf.constant([[2], [3], [5], [7]]) # The indices where we want to update the values
data = tf.constant([1, 3, 5, 7]) # The value which is to be inserted
print(tf.scatter_nd(indices=indices,
                   updates=data,
                   shape=t6))
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor([0 0 1 3 0 5 0 7 0 0], shape=(10,), dtype=int32)

The method of tf.scatter_nd has a demerit that it requires a zero-initialized tensor.

 

Code

# Gathering values from a previously created tensor by specifying indices
new_indices = tf.constant([[1, 2], [3, 1], [2, 3]])
t7 = tf.gather_nd(t2, indices=new_indices)
print(t7)
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor([ 5 16 13], shape=(3,), dtype=int32)

 

We can also add values of a tensor into another tensor.

Code

# Adding the contents of tensor t7 to tensor t8
t8 = tf.scatter_nd(indices=new_indices, updates=t7, shape=tf.constant([4, 5]))
print(t8)
You can also try this code with Online Python Compiler
Run Code


Output

tf.Tensor(
[[ 0  0  0  0  0]
[ 0  0  5  0  0]
[ 0  0  0 13  0]
[ 0 16  0  0  0]], shape=(4, 5), dtype=int32)


Alright! Now we hope you understand Tensorflow Advanced: Tensor Slicing.

Frequently Asked Questions

What is a tensor?

A tensor is an algebraic object that describes a multilinear relationship between sets of algebraic objects related to a vector space. 

What is the difference between a tensor and a matrix?

A tensor is an n-dimensional array satisfying a particular transformation law. Unike a matrix, it shows an object placed in a specific coordinate system.

What are the common libraries used for machine learning?

The common libraries used for machine learning are NumPy, Pandas, Scikit learn, NLTK, PyTorch, TensorFlow, etc.

Why is TensorFlow faster than PyTorch?

TensorFlow offers better visualisation, which allows developers to debug and track the training process easily. However, PyTorch provides only limited visualisation.

What is PyTorch?

PyTorch is a machine learning framework used for computer vision and natural language processing. It is free and easy to use.

Conclusion

In this article, we discussed Tensorflow Advanced: Tensor Slicing. We learnt how to create a tensor, about 1-D and 2-D tensors, and to slice tensors in TensorFlow.

We hope this blog on Tensorflow Advanced: Tensor Slicing was helpful. You can also refer to other similar articles.


You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning Ninja!

Live masterclass