Today, I wanted to mess around with something in NumPy called `*`. I’d seen it before but never really dug into it. So, I fired up my trusty Jupyter Notebook and got started.
What I Did First
First things first, I needed to import NumPy. That’s the easy part:
import numpy as np
Then, I tried the most basic thing I could think of, just creating indices for a simple grid. I picked a (2, 3) shape, just to see what would happen:
grid_indices = *((2, 3))
print(grid_indices)
What I Saw
Okay, this was the interesting part. The output looked like this:
[[[0 0 0]
[1 1 1]]
[[0 1 2]
[0 1 2]]]
It’s an array with shape (2, 2, 3). At first, I was a little confused, so to try and understand what it represented I went step by step, to understand the shape of the output. The first element of the shape, tells me the number of sub-arrays that are stacked together, which is two.
So I have an array stacked on top of another, where the first array represents row indices, and the second array represents column indices. I visualized how the numbers increment.
Playing Around
I wanted to see what happened with different shapes. So I tried a few more:
(3, 3): Got a (2, 3, 3) array. The row indices were [[0, 0, 0], [1, 1, 1], [2, 2, 2]], and the column indices were [[0, 1, 2], [0, 1, 2], [0, 1, 2]].
(1, 4): This gave me a (2, 1, 4) array. Row indices: [[0, 0, 0, 0]]. Column indices: [[0, 1, 2, 3]].
(4,1):Similar to before I got a (2,4,1) array. Row indices: [[0],[1],[2],[3]]. Column Indicies: [[0],[0],[0],[0]]
I started to get the pattern. It’s always creating two arrays. The first one gives you the row index for each position, and the second one gives you the column index.
A Little “Aha!” Moment
I realized that I could use this to create coordinates. For example, if I had some data in a 2×3 array and I wanted to know the (row, column) position of each element, `*` would give me that directly. It generates a grid of coordinates that mirrors the shape, where each position shows its location in the grid.
I’m not sure yet how this would help me in my machine-learning journey, but it seems helpful.