注意
点击 这里 下载完整示例代码
学习基础知识 || 快速入门 || 张量 || 数据集和数据加载器 || 转换 || 构建模型 || 自动求导 || 优化 || 保存和加载模型
张量¶
创建时间:2021年2月10日 | 最后更新:2024年1月16日 | 最后验证:2024年11月5日
张量是一种特殊的数据结构,与数组和矩阵非常相似。 在 PyTorch 中,我们使用张量来编码模型的输入和输出,以及模型的参数。
张量类似于 NumPy的 ndarray,除了张量可以在GPU或其他硬件加速器上运行。实际上,张量和 NumPy数组通常可以共享相同的底层内存,从而消除了复制数据的需要(参见 与NumPy的桥梁)。张量 还针对自动微分进行了优化(我们将在Autograd 部分进一步了解)。如果你熟悉ndarray,你会对张量API感到得心应手。如果不熟悉,请继续学习!
import torch
import numpy as np
初始化一个张量¶
张量可以通过多种方式初始化。以下是一些示例:
直接从数据
张量可以直接从数据创建,数据类型会自动推断。
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
从NumPy数组
张量可以从NumPy数组创建(反之亦然 - 请参阅 与NumPy的桥梁)。
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
从另一个张量:
新的张量继承了Argument张量的属性(形状、数据类型),除非明确覆盖。
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.8823, 0.9150],
[0.3829, 0.9593]])
使用随机值或常数值:
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.3904, 0.6009, 0.2566],
[0.7936, 0.9408, 0.1332]])
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
张量操作¶
超过 100 种张量操作,包括算术、线性代数、矩阵操作(转置、 索引、切片)、采样等在这里有详细的描述 这里。
这些操作可以在GPU上运行(通常速度比在CPU上快)。如果你使用的是Colab,请前往Runtime > Change runtime type > GPU以分配一个GPU。
默认情况下,张量在CPU上创建。我们需要显式地使用
.to 方法将张量移动到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_like索引和切片:
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 将一系列张量沿给定维度连接起来。
另见 torch.stack,
另一个张量拼接操作符,与 torch.cat 略有不同。
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数值:
12.0 <class 'float'>
原地操作
将结果存储到操作数中的操作称为原地操作。它们由_后缀表示。
例如:x.copy_(y),x.t_(),将会改变x。
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.]])
注意
就地操作可以节省一些内存,但计算导数时可能会出现问题,因为它们会导致历史记录立即丢失。因此,建议避免使用就地操作。
Bridge with 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: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
NumPy数组转Tensor¶
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.]
脚本总运行时间: ( 0 分钟 0.024 秒)