# A Gentle Introduction to Tensors for Machine Learning with NumPy

Last Updated on

In deep learning it is common to see a lot of discussion around tensors as the cornerstone data structure.

Tensor even appears in name of Google’s flagship machine learning library: “TensorFlow“.

Tensors are a type of data structure used in linear algebra, and like vectors and matrices, you can calculate arithmetic operations with tensors.

In this tutorial, you will discover what tensors are and how to manipulate them in Python with NumPy

After completing this tutorial, you will know:

• That tensors are a generalization of matrices and are represented using n-dimensional arrays.
• How to implement element-wise operations with tensors.
• How to perform the tensor product.

Discover vectors, matrices, tensors, matrix types, matrix factorization, PCA, SVD and much more in my new book, with 19 step-by-step tutorials and full source code.

Let’s get started.

• Update Oct/2019: Fixed typo in the names of array indexes (thanks Henry Chan). A Gentle Introduction to Tensors for Machine Learning with NumPy
Photo by Daniel Lombraña González, some rights reserved.

## Tutorial Overview

This tutorial is divided into 3 parts; they are:

1. What are Tensors?
2. Tensors in Python
3. Element-Wise Tensor Operations
4. Tensor Product

### Need help with Linear Algebra for Machine Learning?

Take my free 7-day email crash course now (with sample code).

Click to sign-up and also get a free PDF Ebook version of the course.

## What are Tensors?

A tensor is a generalization of vectors and matrices and is easily understood as a multidimensional array.

In the general case, an array of numbers arranged on a regular grid with a variable number of axes is known as a tensor.

— Page 33, Deep Learning, 2016.

A vector is a one-dimensional or first order tensor and a matrix is a two-dimensional or second order tensor.

Tensor notation is much like matrix notation with a capital letter representing a tensor and lowercase letters with subscript integers representing scalar values within the tensor.

Many of the operations that can be performed with scalars, vectors, and matrices can be reformulated to be performed with tensors.

As a tool, tensors and tensor algebra is widely used in the fields of physics and engineering. It is a term and set of techniques known in machine learning in the training and operation of deep learning models can be described in terms of tensors.

## Tensors in Python

Like vectors and matrices, tensors can be represented in Python using the N-dimensional array (ndarray).

A tensor can be defined in-line to the constructor of array() as a list of lists.

The example below defines a 3x3x3 tensor as a NumPy ndarray. Three dimensions is easier to wrap your head around. Here, we first define rows, then a list of rows stacked as columns, then a list of columns stacked as levels in a cube.

Running the example first prints the shape of the tensor, then the values of the tensor itself.

You can see that, at least in three-dimensions, the tensor is printed as a series of matrices, one for each layer. For this 3D tensor, axis 0 specifies the level, axis 1 specifies the row, and axis 2 specifies the column.

## Element-Wise Tensor Operations

As with matrices, we can perform element-wise arithmetic between tensors.

In this section, we will work through the four main arithmetic operations.

The element-wise addition of two tensors with the same dimensions results in a new tensor with the same dimensions where each scalar value is the element-wise addition of the scalars in the parent tensors.

Running the example prints the addition of the two parent tensors.

### Tensor Subtraction

The element-wise subtraction of one tensor from another tensor with the same dimensions results in a new tensor with the same dimensions where each scalar value is the element-wise subtraction of the scalars in the parent tensors.

In NumPy, we can subtract tensors directly by subtracting arrays.

Running the example prints the result of subtracting the first tensor from the second.

The element-wise multiplication of one tensor from another tensor with the same dimensions results in a new tensor with the same dimensions where each scalar value is the element-wise multiplication of the scalars in the parent tensors.

As with matrices, the operation is referred to as the Hadamard Product to differentiate it from tensor multiplication. Here, we will use the “o” operator to indicate the Hadamard product operation between tensors.

In NumPy, we can multiply tensors directly by multiplying arrays.

Running the example prints the result of multiplying the tensors.

### Tensor Division

The element-wise division of one tensor from another tensor with the same dimensions results in a new tensor with the same dimensions where each scalar value is the element-wise division of the scalars in the parent tensors.

In NumPy, we can divide tensors directly by dividing arrays.

Running the example prints the result of dividing the tensors.

## Tensor Product

The tensor product operator is often denoted as a circle with a small x in the middle. We will denote it here as “(x)”.

Given a tensor A with q dimensions and tensor B with r dimensions, the product of these tensors will be a new tensor with the order of q + r or, said another way, q + r dimensions.

The tensor product is not limited to tensors, but can also be performed on matrices and vectors, which can be a good place to practice in order to develop the intuition for higher dimensions.

Let’s take a look at the tensor product for vectors.

Or, unrolled:

Let’s take a look at the tensor product for matrices.

Or, unrolled:

The tensor product can be implemented in NumPy using the tensordot() function.

The function takes as arguments the two tensors to be multiplied and the axis on which to sum the products over, called the sum reduction. To calculate the tensor product, also called the tensor dot product in NumPy, the axis must be set to 0.

In the example below, we define two order-1 tensors (vectors) with and calculate the tensor product.

Running the example prints the result of the tensor product.

The result is an order-2 tensor (matrix) with the lengths 2×2.

The tensor product is the most common form of tensor multiplication that you may encounter, but there are many other types of tensor multiplications that exist, such as the tensor dot product and the tensor contraction.

## Extensions

This section lists some ideas for extending the tutorial that you may wish to explore.

• Update each example using your own small contrived tensor data.
• Implement three other types of tensor multiplication not covered in this tutorial with small vector or matrix data.
• Write your own functions to implement each tensor operation.

If you explore any of these extensions, I’d love to know.

This section provides more resources on the topic if you are looking to go deeper.

## Summary

In this tutorial, you discovered what tensors are and how to manipulate them in Python with NumPy.

Specifically, you learned:

• That tensors are a generalization of matrices and are represented using n-dimensional arrays.
• How to implement element-wise operations with tensors.
• How to perform the tensor product.

Do you have any questions?

## Get a Handle on Linear Algebra for Machine Learning! #### Develop a working understand of linear algebra

...by writing lines of code in python

Discover how in my new Ebook:
Linear Algebra for Machine Learning

It provides self-study tutorials on topics like:
Vector Norms, Matrix Multiplication, Tensors, Eigendecomposition, SVD, PCA and much more...

### 24 Responses to A Gentle Introduction to Tensors for Machine Learning with NumPy

1. Laique Merlin Djeutchouang February 14, 2018 at 7:29 pm #

Hi Jason!

Very nice, simple and well detailed introduction to one of the key mathematical tools for deep learning. I think any amateur in tensor could easily take over from here.

• Jason Brownlee February 15, 2018 at 8:40 am #

Thanks.

2. Dhananjay May 31, 2018 at 12:37 pm #

Hello Jason

This is a fantastic introduction to tensors. Very quick read-through for beginners like me. Very Helpful.

• Jason Brownlee May 31, 2018 at 2:13 pm #

3. Xiwang Li November 3, 2018 at 9:38 am #

Thank you for your blog, which is very helpful. But I have a general question. Why do we need tensors in deep learning. Why not just use Numpy arrays?

• Jason Brownlee November 4, 2018 at 6:23 am #

You can develop your own library using numpy arrays.

Tensors are simply a generalisation of matrices.

4. justin January 15, 2019 at 9:37 am #

“Given a tensor A with q dimensions and tensor B with r dimensions, the product of these tensors will be a new tensor with the order of q + r or, said another way, q + r dimensions.”

• Victor July 7, 2019 at 8:45 am #

Good tutorial, with a very clear definition. I think the tensor dot product is probably the most tricky of the operators as you provide a few examples for low dimensions but don’t really provide the general formula for order n by order m. I think it would also be helpful to relate what tensor are used for when representing concepts for deep learning.

• Jason Brownlee July 8, 2019 at 8:35 am #

Thanks Victor.

5. Sebastian February 25, 2019 at 8:07 pm #

Thank you, well-summarized!

• Jason Brownlee February 26, 2019 at 6:18 am #

6. Ahmad June 13, 2019 at 1:49 am #

Nice stuff but I wish you had decompositions and other things as well. Thanks, it is well-written.

7. Mahalingam June 29, 2019 at 9:11 pm #

this is totally different from matrix multiplication. in matrix dimenion is definedas A mxn where the matrix A has dimension m rows and n columns.

8. Abraham July 16, 2019 at 5:01 am #

Hi Jason!
I have one question about tensor conversion.İ am using attention mechanism,and I must do my operations in for loop so that i store my results in a list.At the end,i cannot convert the list into a tensor in order to make the results connected with dense layers.Can u suggest anything to come over this problem?

• Jason Brownlee July 16, 2019 at 8:24 am #

A list or a numpy array can represent a tensor.

I think you might mean a Tensor data type for a given library? Perhaps check the library API on how to convert lists and arrays to that type?

9. sunny1304 July 25, 2019 at 2:22 am #

Very nice tutorial.
I am no expert in math, but isn’t vector is a special type of tensor not the other way around ?

Thanks.

• Jason Brownlee July 25, 2019 at 7:57 am #

Not really, but it could be framed that way.

10. Vladimir September 4, 2019 at 12:39 am #

Well explained. And easy to understand!

• Jason Brownlee September 4, 2019 at 6:00 am #

11. Henry Chan October 22, 2019 at 11:06 am #

Hi Jason,

You said that “For this 3D tensor, axis 0 specifies the level, axis 1 specifies the column, and axis 2 specifies the row.”

But I think I should be:
For this 3D tensor, axis 0 specifies the level, axis 1 specifies the row, and axis 2 specifies the column.

A = array([
[[1,2,3], [4,5,6], [7,8,9]],
[[11,12,13], [14,15,16], [17,18,19]],
[[21,22,23], [24,25,26], [27,28,29]]
])

Wint zero index, we will have:

print(A[0,0,0]) –> 1: Level 0, Row 0, Column 0
print(A[0,0,1]) –> 2: Level 0, Row 0, Column 1
print(A[0,1,0]) –> 4: Level 0, Row 2, Column 0

Correct me if I wrong.
Thanks

• Jason Brownlee October 22, 2019 at 1:48 pm #

Thanks.

Also try this:

Which prints:

[1 2 3]
[1 4 7]

12. Yansen Xiao December 6, 2019 at 2:42 am #

In all the addition, subtraction, product, and division examples, I see this:
b111, b121, t131
B = (b211, t221, t231)

Should the “t” be “b”? I am totally new in tensor and this is the first time I am learning it.

• Jason Brownlee December 6, 2019 at 5:22 am #

Looks like a typo, thanks.

Fixed.