张量
张量是一种专用数据结构,与数组和矩阵非常相似。在PyTorch中,我们使用张量来编码模型的输入、输出以及模型的参数。
张量与NumPy的ndarray类似,区别在于张量可以在GPU或其他硬件加速器上运行。事实上,张量和NumPy数组通常可以共享底层内存,无需复制数据。张量同样针对自动微分进行了优化。如果你熟悉ndarray,就能轻松上手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")Ones Tensor: tensor([[1, 1], [1, 1]]) Random Tensor: tensor([[0.6027, 0.8237], [0.1513, 0.9539]])
使用随机值或常量值创建:
shape是张量维度的元组,在以下函数中,它决定了输出张量的维度。
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}")Random Tensor: tensor([[0.3726, 0.6270, 0.0221], [0.3587, 0.8808, 0.5374]]) Ones Tensor: tensor([[1., 1., 1.], [1., 1., 1.]]) Zeros Tensor: tensor([[0., 0., 0.], [0., 0., 0.]])
张量的属性
张量属性描述了它们的形状、数据类型以及存储的设备。
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
张量的操作
PyTorch提供了超过1200种张量操作,包括算术运算、线性代数、矩阵操作、采样等。
这些操作都可以在CPU和加速器上运行。默认情况下,张量在CPU上创建,需要使用.to方法显式将张量移动到加速器。请注意,跨设备复制大型张量在时间和内存上的开销很大!
# We move our tensor to the current accelerator if available if torch.accelerator.is_available(): tensor = tensor.to(torch.accelerator.current_accelerator())
尝试列表中的一些操作。如果你熟悉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.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)
tensor([[1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.]])
单元素张量 如果你有一个单元素张量,例如将张量的所有值聚合为一个值,可以使用item()将其转换为Python数值:
agg = tensor.sum() agg_item = agg.item() print(agg_item, type(agg_item))
12.0
原地操作 将结果存储到操作数中的操作称为原地操作,它们带有_后缀。例如:x.copy_(y),x.t_(),会改变x。
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)tensor([[1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.]]) tensor([[6., 5., 6., 6.], [6., 5., 6., 6.], [6., 5., 6., 6.], [6., 5., 6., 6.]])
注意
原地操作可以节省一些内存,但在计算导数时可能会出现问题,因为会立即丢失历史记录。因此,不建议使用它们。
与NumPy的桥梁
CPU上的张量和NumPy数组可以共享底层内存位置,修改其中一个会改变另一个。
张量转换为NumPy数组
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")t: tensor([1., 1., 1., 1., 1.]) n: [1. 1. 1. 1. 1.]
张量的变化会反映在NumPy数组中。
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")t: tensor([2., 2., 2., 2., 2.]) n: [2. 2. 2. 2. 2.]
NumPy数组转换为张量
n = np.ones(5) t = torch.from_numpy(n)
NumPy数组的变化会反映在张量中。
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64) n: [2. 2. 2. 2. 2.]