关于程序员:PyTorch张量操作详解

11次阅读

共计 1313 个字符,预计需要花费 4 分钟才能阅读完成。

前言

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 设施上。

正文完
 0