How to shuffle columns or rows of matrix in PyTorch?

PyTorchServer Side ProgrammingProgramming

A matrix in PyTorch is a 2-dimension tensor having elements of the same dtype. We can shuffle a row by another row and a column by another column. To shuffle rows or columns, we can use simple slicing and indexing as we do in Numpy.

  • If we want to shuffle rows, then we do slicing in the row indices.

  • To shuffle columns, we do slicing in the column indices.

  • For example, if we want to shuffle the 1st and 2nd rows of a 3☓3 matrix, then we just shuffle the index of these rows and make a slicing to find the shuffled matrix.

Let's take a couple of examples to have a better understanding of how it works.

Steps

You could use the following steps to shuffle the rows or columns of a matrix.

  • Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it.

import torch
  • Define a matrix and print it.

matrix = torch.tensor([[1., 2., 3.],[4., 5., 6.],[7, 8, 9]])
print("Original Matrix:
", matrix)
  • Specify the row and column indices with shuffled indices. In the following example we shuffle 1st and 2nd row. So, we interchanged the indices of these rows.

# shuffle 1st and second row
r = torch.tensor([1, 0, 2])
c = torch.tensor([0, 1, 2])
  • Shuffle the rows or columns of the matrix.

matrix=matrix[r[:, None], c] # shuffles rows
matrix = matrix[r][:,c] # shuffles columns
  • Print the shuffled matrix.

print("Shuffled Matrix:
", matrix)

Example 1

In the following example, we shuffle the 1st and 2nd rows.

# Import the required library
import torch

# create a matrix
matrix = torch.tensor([[1., 2., 3.],[4., 5., 6.],[7, 8, 9]])

# print matrix
print("Original Matrix:
", matrix) # shuffle 1st and second row r = torch.tensor([1, 0, 2]) c = torch.tensor([0, 1, 2]) matrix=matrix[r[:, None], c] print("Shuffled Matrix:
", matrix)

Output

Original Matrix:
   tensor([[1., 2., 3.],
      [4., 5., 6.],
      [7., 8., 9.]])
Shuffled Matrix:
   tensor([[4., 5., 6.],
      [1., 2., 3.],
      [7., 8., 9.]])

Notice that the 1st and 2nd rows are shuffled.

Example 2

In the following example, we shuffle 2nd and 3rd columns.

# Import the required library
import torch

# create a matrix
matrix = torch.tensor([[1., 2., 3.],[4., 5., 6.],[7, 8, 9]])

# print matrix
print("Original Matrix:
", matrix) # shuffle 2nd and 3rd columns r = torch.tensor([0, 1, 2]) c = torch.tensor([0, 2, 1]) matrix_col_Shuffled = matrix[r][:,c] print("Shuffled Matrix:
", matrix_col_Shuffled)

Output

Original Matrix:
   tensor([[1., 2., 3.],
      [4., 5., 6.],
      [7., 8., 9.]])
Shuffled Matrix:
   tensor([[1., 3., 2.],
      [4., 6., 5.],
      [7., 9., 8.]])
raja
Updated on 20-Jan-2022 07:06:23

Advertisements