2.2 张量

发布时间 2023-04-09 00:03:43作者: 周XX

张量

张量是一种特殊的数据结构,与数组和矩阵非常相似。 在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。

张量类似于 NumPy 的 ndarray,此外张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存,无需复制数据。张量还针对自动微分进行了优化。如果你熟悉ndarrays,那么你就会对Tensor API了如指掌。如果没有,请往下看!

import torch
import numpy as np

初始化张量

张量可以通过多种方式初始化。请看以下示例:

直接来自数据

张量可以直接从数据创建。数据类型是自动推断的。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

从NumPy数组

张量可以从NumPy数组中创建。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

从另一个张量

除非显式重写,否则新张量保留参数张量的属性(形状、数据类型)。

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

使用随机值或常数值:

形状是张量维度的元组。在下面的函数中,它决定了输出张量的维数。

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")

张量的属性

张量属性描述它们的形状、数据类型和存储它们的设备。

tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
点击查看输出
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

对Tensors的操作

有100多种张量运算,包括算术、线性代数、矩阵操作(换位、索引、切片)、采样等。
这些操作中的每一个都可以在GPU上运行(通常比在CPU上运行的速度更快)。如果您正在使用Colab,请转到“运行时”>“更改运行时类型”>“GPU”来分配GPU。
默认情况下,张量是在CPU上创建的。我们需要使用方法(在检查GPU可用性之后)明确地将张量移动到GPU。请记住,在设备之间复制大张量在时间和内存方面可能会很昂贵!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to("cuda")

尝试列表中的一些操作。如果你熟悉NumPy API,你会发现Tensor API很容易使用。

标准的类似numpy的索引和切片:

tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
点击查看输出
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

连接张量

您可以使用沿着给定维度连接张量序列。另请参阅torch.stack,这是另一个张量连接选项,与.torch.cattorch.cat略有不同

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
点击查看输出
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

算术运算

# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)


# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

单元素张量

如果您有一个单元素张量,例如,通过将张量的所有值聚合为一个值,您可以使用item()将其转换为Python数值:

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))

就地操作

将结果存储到操作数中的操作称为就地调用。它们用后缀表示。例如:x.copy_(y), x.t_(), 将会改变 x.

print(f"{tensor} \n")
tensor.add_(5)
print(tensor)

返回目录