认识Pytorch中的二维张量

145 阅读6分钟

二维张量类似于二维度量。与二维度量一样,二维张量也有nn的行数和列数。

让我们以灰度图像为例,它是一个由数值组成的二维矩阵,通常被称为像素。从'0'到'255',每个数字代表一个像素强度值。这里,最低强度的数字(即'0')代表图像中的黑色区域,而最高强度的数字(即'255')代表图像中的白色区域。使用PyTorch框架,这个二维图像或矩阵可以被转换为二维张量。

在上一篇文章中,我们了解了PyTorch中的一维张量,并应用了一些有用的张量操作。在本教程中,我们将使用PyTorch库将这些操作应用到二维张量中。具体来说,我们将学习。

  • 如何在PyTorch中创建二维张量并探索其类型和形状。
  • 关于二维张量的切片和索引操作的详细内容。
  • 要对张量应用一些方法,如,张量加法、乘法等。

让我们开始吧。

教程概述

本教程分为几个部分:

  • 二维张量的类型和形状
  • 将二维张量转换为NumPy数组
  • 将pandas系列转换为二维张量
  • 对二维张量的索引和切片操作
  • 对二维张量的操作

二维标量的类型和形状

让我们首先导入一些我们将在本教程中使用的必要库。

import torch
import numpy as np 
import pandas as pd

为了检查二维张量的类型和形状,我们将使用之前为一维张量介绍的PyTorch的相同方法。但是,它的工作方式应该和一维张量一样吗?

让我们通过将一个二维整数列表转换为一个二维张量对象来演示。作为一个例子,我们将创建一个二维列表并应用torch.tensor() 进行转换。

example_2D_list = [[5, 10, 15, 20],
                   [25, 30, 35, 40],
                   [45, 50, 55, 60]]
list_to_tensor = torch.tensor(example_2D_list)
print("Our New 2D Tensor from 2D List is: ", list_to_tensor)
Our New 2D Tensor from 2D List is:  tensor([[ 5, 10, 15, 20],
        [25, 30, 35, 40],
        [45, 50, 55, 60]])

正如你所看到的,torch.tensor() 方法对二维张量也很有效。现在,让我们使用shape(),size(), 和ndimension() 方法来返回张量对象的形状、大小和尺寸。

print("Getting the shape of tensor object: ", list_to_tensor.shape)
print("Getting the size of tensor object: ", list_to_tensor.size())
print("Getting the dimensions of tensor object: ", list_to_tensor.ndimension())
print("Getting the shape of tensor object: ", list_to_tensor.shape)
print("Getting the size of tensor object: ", list_to_tensor.size())
print("Getting the dimensions of tensor object: ", list_to_tensor.ndimension())

将二维张量转换为NumPy数组

PyTorch允许我们将二维张量转换为NumPy数组,然后再转换回张量。让我们来了解一下。

# Converting two_D tensor to numpy array

twoD_tensor_to_numpy = list_to_tensor.numpy()
print("Converting two_Dimensional tensor to numpy array:")
print("Numpy array after conversion: ", twoD_tensor_to_numpy)
print("Data type after conversion: ", twoD_tensor_to_numpy.dtype)

print("***************************************************************")

# Converting numpy array back to a tensor

back_to_tensor = torch.from_numpy(twoD_tensor_to_numpy)
print("Converting numpy array back to two_Dimensional tensor:")
print("Tensor after conversion:", back_to_tensor)
print("Data type after conversion: ", back_to_tensor.dtype)
Converting two_Dimensional tensor to numpy array:
Numpy array after conversion:  [[ 5 10 15 20]
 [25 30 35 40]
 [45 50 55 60]]
Data type after conversion:  int64
***************************************************************
Converting numpy array back to two_Dimensional tensor:
Tensor after conversion: tensor([[ 5, 10, 15, 20],
        [25, 30, 35, 40],
        [45, 50, 55, 60]])
Data type after conversion:  torch.int64

将潘达斯系列转换为二维张量

同样地,我们也可以将pandas DataFrame转换为张量。与一维张量一样,我们将使用同样的步骤进行转换。使用value属性,我们将得到NumPy数组,然后使用torch.from_numpy ,允许你将pandas DataFrame转换为张量。

下面是我们要做的。

# Converting Pandas Dataframe to a Tensor

dataframe = pd.DataFrame({'x':[22,24,26],'y':[42,52,62]})

print("Pandas to numpy conversion: ", dataframe.values)
print("Data type before tensor conversion: ", dataframe.values.dtype)

print("***********************************************")

pandas_to_tensor = torch.from_numpy(dataframe.values)
print("Getting new tensor: ", pandas_to_tensor)
print("Data type after conversion to tensor: ", pandas_to_tensor.dtype)
Pandas to numpy conversion:  [[22 42]
 [24 52]
 [26 62]]
Data type before tensor conversion:  int64
***********************************************
Getting new tensor:  tensor([[22, 42],
        [24, 52],
        [26, 62]])
Data type after conversion to tensor:  torch.int64

二维张量的索引和切分操作

对于索引操作,可以使用方括号访问张量对象中的不同元素。你可以简单地把相应的指数放在方括号中,以访问张量中的所需元素。

在下面的例子中,我们将创建一个张量并使用两种不同的方法访问某些元素。注意,索引值应该总是比元素在二维张量中的位置少一个。

example_tensor = torch.tensor([[10, 20, 30, 40],
                               [50, 60, 70, 80],
                               [90, 100, 110, 120]])
print("Accessing element in 2nd row and 2nd column: ", example_tensor[1, 1])
print("Accessing element in 2nd row and 2nd column: ", example_tensor[1][1])

print("********************************************************")

print("Accessing element in 3rd row and 4th column: ", example_tensor[2, 3])
print("Accessing element in 3rd row and 4th column: ", example_tensor[2][3])
Accessing element in 2nd row and 2nd column:  tensor(60)
Accessing element in 2nd row and 2nd column:  tensor(60)
********************************************************
Accessing element in 3rd row and 4th column:  tensor(120)
Accessing element in 3rd row and 4th column:  tensor(120)

如果我们需要同时访问两个或更多的元素呢?这就是张量切分发挥作用的地方。让我们用前面的例子来访问第二行的前两个元素和第三行的前三个元素。

example_tensor = torch.tensor([[10, 20, 30, 40],
                               [50, 60, 70, 80],
                               [90, 100, 110, 120]])
print("Accessing first two elements of the second row: ", example_tensor[1, 0:2])
print("Accessing first two elements of the second row: ", example_tensor[1][0:2])

print("********************************************************")

print("Accessing first three elements of the third row: ", example_tensor[2, 0:3])
print("Accessing first three elements of the third row: ", example_tensor[2][0:3])
example_tensor = torch.tensor([[10, 20, 30, 40],
                               [50, 60, 70, 80],
                               [90, 100, 110, 120]])
print("Accessing first two elements of the second row: ", example_tensor[1, 0:2])
print("Accessing first two elements of the second row: ", example_tensor[1][0:2])

print("********************************************************")

print("Accessing first three elements of the third row: ", example_tensor[2, 0:3])
print("Accessing first three elements of the third row: ", example_tensor[2][0:3])

对二维张量的操作

虽然你可以使用PyTorch框架对二维张量进行很多操作,但在这里,我们将向你介绍张量加法以及标量和矩阵乘法。

二维张量的加法

两个张量的相加类似于矩阵相加。这是一个相当直接的过程,因为你只需要一个加法(+)运算符来进行操作。让我们在下面的例子中添加两个张量。

A = torch.tensor([[5, 10],
                  [50, 60], 
                  [100, 200]]) 
B = torch.tensor([[10, 20], 
                  [60, 70], 
                  [200, 300]])
add = A + B
print("Adding A and B to get: ", add)
Adding A and B to get:  tensor([[ 15,  30],
        [110, 130],
        [300, 500]])

二维张量的标量和矩阵乘法

二维张量的标量乘法与矩阵的标量乘法也是一样的。例如,将一个张量与一个标量相乘,例如标量4,你就会将张量中的每个元素都乘以4。

new_tensor = torch.tensor([[1, 2, 3], 
                           [4, 5, 6]]) 
mul_scalar = 4 * new_tensor
print("result of scalar multiplication: ", mul_scalar)
result of scalar multiplication:  tensor([[ 4,  8, 12],
        [16, 20, 24]])

说到二维张量的乘法,PyTorch中的torch.mm() ,让我们的事情变得更加简单。与线性代数中的矩阵乘法类似,张量对象A的列数(即2×3)必须等于张量对象B的行数(即3×2)。

A = torch.tensor([[3, 2, 1], 
                  [1, 2, 1]])
B = torch.tensor([[3, 2], 
                  [1, 1], 
                  [2, 1]])
A_mult_B = torch.mm(A, B)
print("multiplying A with B: ", A_mult_B)
multiplying A with B:  tensor([[13,  9],
        [ 7,  5]])

总结

在本教程中,你了解了PyTorch中的二维张量。

具体来说,你学到了

  • 如何在PyTorch中创建二维张量并探索其类型和形状。
  • 关于二维张量的切片和索引操作的详细内容。
  • 要对张量应用一些方法,如,张量加法、乘法等。