如何在 PyTorch 中打乱矩阵的列或行?
PyTorch 中的矩阵是一个二维张量,其元素具有相同的 dtype。我们可以将一行与另一行交换,将一列与另一列交换。要打乱行或列,我们可以像在 Numpy 中一样使用简单的**切片**和**索引**。
如果我们想打乱行,那么我们在行索引中进行切片。
要打乱列,我们在列索引中进行切片。
例如,如果我们想打乱 3×3 矩阵的第 1 行和第 2 行,那么我们只需打乱这些行的索引并进行切片以找到打乱后的矩阵。
让我们看几个例子,以便更好地理解它是如何工作的。
步骤
您可以使用以下步骤来打乱矩阵的行或列。
导入所需的库。在以下所有示例中,所需的 Python 库是**torch**。确保您已安装它。
import torch
定义一个矩阵并打印它。
matrix = torch.tensor([[1., 2., 3.],[4., 5., 6.],[7, 8, 9]])
print("Original Matrix:
", matrix)指定行和列索引以及打乱后的索引。在以下示例中,我们打乱第 1 行和第 2 行。因此,我们交换了这些行的索引。
# shuffle 1st and second row r = torch.tensor([1, 0, 2]) c = torch.tensor([0, 1, 2])
打乱矩阵的行或列。
matrix=matrix[r[:, None], c] # shuffles rows matrix = matrix[r][:,c] # shuffles columns
打印打乱后的矩阵。
print("Shuffled Matrix:
", matrix)示例 1
在以下示例中,我们打乱第 1 行和第 2 行。
# 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)输出
Original Matrix: tensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) Shuffled Matrix: tensor([[4., 5., 6.], [1., 2., 3.], [7., 8., 9.]])
请注意,第 1 行和第 2 行已打乱。
示例 2
在以下示例中,我们打乱第 2 列和第 3 列。
# 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)输出
Original Matrix: tensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) Shuffled Matrix: tensor([[1., 3., 2.], [4., 6., 5.], [7., 9., 8.]])
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP