目录

了解基础知识 ||快速入门 ||张量 ||数据集和数据加载器 ||变换 ||构建模型 ||Autograd ||优化 ||保存并加载模型

Tensors

创建时间: 2021年2月10日 |上次更新时间:2024 年 1 月 16 日 |上次验证: Nov 05, 2024

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

张量类似于 NumPy 的 ndarrays,不同之处在于张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存,无需复制数据(请参阅使用 NumPy 的 Bridge)。张 还针对自动微分进行了优化(我们将在后面的 Autograd 部分看到更多相关信息)。如果您熟悉 ndarrays,那么您将熟悉 Tensor API。如果没有,请继续关注!

import torch
import numpy as np

初始化 Tensor

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

直接来自数据

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

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

从 NumPy 数组

可以从 NumPy 数组创建张量(反之亦然 - 请参阅 Bridge with 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.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 的属性

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

对 Tensor 的操作

超过 100 种张量运算,包括算术、线性代数、矩阵操作(转置、 indexing, slicing)、sampling 等是 此处进行了全面描述。

这些操作中的每一个都可以在 GPU 上运行(通常比在 GPU 上的 CPU)。如果您使用的是 Colab,请转至 Runtime > Change runtime type > GPU 来分配 GPU。

默认情况下,张量是在 CPU 上创建的。我们需要使用 method 将张量显式移动到 GPU(在检查 GPU 可用性之后)。请记住,复制大型张量 跨设备在时间和内存方面可能很昂贵!.to

# 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, 另一个与 . 略有不同的 Tensor Joining 运算符。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)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

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

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
12.0 <class 'float'>

就地操作将结果存储到操作数中的操作称为就地调用。它们由后缀表示。 例如: , , 将更改 ._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 数组上的张量可以共享其底层内存 locations 的 Locations,更改一个位置将更改另一个位置。

Tensor 到 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 数组到 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 秒)

由 Sphinx-Gallery 生成的图库

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源