NumPy: Master the Shape/Dimension of your matrix with this simple trick.

TC. Lin
3 min readJan 18, 2023

--

NumPy is the library that is known as the backbone of data science that dominates numerical computing in Python. This is because it is really useful when performing numerical calculations with good performance, especially when dealing with vectors (arrays) and matrices.

However, the problem is that it is very hard to get our heads around matrices at higher dimensions when we first started with NumPy. For example, what if we have a matrix with shape = (2, 3, 1, 4):

Array with shape (2, 3, 1, 4)

How do we go about understanding it?

Photo by Timothy Dykes on Unsplash

Don’t worry, with this simple trick that I am about to share, you will never be intimidated by arrays with high dimensions.

Let’s get started with a simple vector.

np.ones((1,5))

Output:

(1, 5)

This is a rather simple one, an array with shape = (1, 5), that is, 5 columns and 1 row.

Alright, let’s level it up a little bit.

What if we have another array with the shape = (2, 5)? Yeap. You guessed it.

The latter corresponds to the number of columns, and the former corresponds to the number of rows.

(2, 5)

Easy? Let’s try a harder one.

What is the shape of the following array:

What is the shape of this array?

Well, there is no any difference with the rule that we just learnt. The shape of this array is (3, 2, 4).

We start with the last number of the shape, 4: 4 Columns.
Then, we move forward a position of the shape, 2: 2 Rows.
As this array is a higher dimension array, the first number is the number of this kind of (2, 4) array, that is — 3: 3 of the same kind.

See! It isn’t that hard right? Remeber, to understand the array:

We always start with the inner side of the array & the last number of the shape of the array, and move our way forward.

Shape — (4, 3, 5)

Let’s try to understand this array with shape = (4, 3, 5)

First step: there is total of 5 columns.
Second step: there is total of 3 rows.
Third step: there are total of 4 of this type of array.

Voila! After understanding this concept, it is simple and straight forward, isn’t it?

With this trick, I bet that the dimensions of a NumPy array will never be a problem again. Enjoy!

Photo by Àlex Rodriguez on Unsplash

--

--

TC. Lin

Predicting the future isn't magic, it's artificial intelligence.