前言
PyTorch 建立在张量之上,PyTorch 张量是一个 n 维数组,类似于 NumPy 数组。如果对 NumPy 较为熟悉,我们会在使用张量时看到语法上的相似之处:
在本节中,我们将学习如何定义和更改张量,将张量转换为数组,以及在计算设备之间移动张量。
定义张量数据类型
默认张量数据类型是 torch.float32,这是张量运算最常用的数据类型。
定义一个具有默认数据类型的张量:
x = torch.ones(2, 2)
print(x)
print(x.dtype)
定义张量时指定数据类型:
x = torch.ones(2, 2, dtype=torch.int8)
print(x)
print(x.dtype)
更改张量的数据类型
我们可以使用 type() 方法更改张量的数据类型:
x=torch.ones(1,dtype=torch.uint8)
print(x.dtype)
更改张量数据类型:
x=x.type(torch.float)
print(x.dtype)
将张量转换为 NumPy 数组
我们可以非常方便地将 PyTorch 张量转换为 NumPy 数组。
x=torch.rand(2,2)
print(x)
print(x.dtype)
y=x.numpy()
print(y)
print(y.dtype)
将 NumPy 数组转换为张量
import numpy as np
x=np.zeros((2,2),dtype=np.float32)
print(x)
print(x.dtype)
y=torch.from_numpy(x)
print(y)
print(y.dtype)
在设备之间移动张量
默认情况下,PyTorch 张量存储在 CPU 上,PyTorch 张量可以在使用 GPU 来加速计算。这是张量与 NumPy 数组相比的主要优势。为了利用这一优势,我们需要将张量移动到 CUDA 设备上,我们可以使用 to() 方法将张量移动到其它可用设备上。
x=torch.tensor([1.5, 2])
print(x)
print(x.device)
if torch.cuda.is_available():
device = torch.device("cuda:0")
x = x.to(device)
print(x)
print(x.device)
device = torch.device("cpu")
x = x.to(device)
print(x)
print(x.device)
device = torch.device("cuda:0")
x = torch.ones(2,2, device=device)
print(x)
在本节中,我们首先定义了一个张量,获得了张量类型,并改变了它的类型。然后,我们将 PyTorch 张量转换为 NumPy 数组,然后进行相反的转换操作。同时,我们还介绍了如何使用 type() 方法更改张量数据类型。然后,我们学习了如何使用 numpy() 方法将 PyTorch 张量转换为 NumPy 数组。
之后,我们使用 from_numpy(x) 方法将 NumPy 数组转换为 PyTorch 张量。然后,我们向学习了如何使用 to() 方法将张量在 CPU 和 CUDA 设备之间移动;如果创建张量时不指定设备,则张量将默认创建在 CPU 设备上。