PyTorch’s Scatter_() Function + One-Hot Encoding (A Visual Explanation)

The way PyTorch’s scatter_(dim, index, src) function works can be a bit confusing. So, I will take a visual approach in explaining the function as I believe it will be more clearer in grasping the concept further.

The scatter_() function takes three arguments: The dimension across which we will be filling out the data. If dim=0, this means that we will be filling the data across the rows, and if dim=1, we will be filling the data across the columns.

The second argument, index, is where in the respective dimension (row or column) the value to fill out will be placed. The third argument, src, represents the values we would like to fill out in the tensor upon which the scatter_() function will be affected. This can be a scalar or a tensor of values.

Let’s take an example to make things more clearer.

Let’s break this step-by-step. What is done here is scattering the value “1” (src) across the rows (dim=0) of the affected tensor (input_tensor), which is a zeros tensor in our case.

I also show here a way to determine the number of rows and columns in input_tensor, provided that the dimension we fill out the values across (i.e. rows) needs to be at least the same value as the dimension in index_tensor, unless there is an index value in the index_tensor which is higher. For instance, index “3” means that we need to have 4 rows, which is greater than the number of rows in index_tensor. Since the affection will be across the rows (dim=0), the number of columns will be the same as those in index_tensor.

The figure below depicts how we select the indices in index_tensor across the rows (dim=0), and map them to input_tensor.

Let’s write what we’ve done above in PyTorch, and it would also be an opportunity for us to check if our input_tensor is correct.

So, yep, we got that right!

What happens when dim=1? That is, filling the values in the respective index across the columns of input_tensor; the figures below depict the changes that will occur.

This is what the above would look like in PyTorch.

One-hot encoding

Using the above, we can now easily do one-hot encoding using PyTorch. The following code shows us how we can do just that.

So yes, that was it for this tutorial. Hope you got a more sense of PyTorch’s scatter_() function, and don’t hesitate to ask any questions or comment below.



Research Fellow @ Massachusetts General Hospital/Harvard Medical School |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store