备注
点击 这里 下载完整示例代码
张量¶
Created On: Mar 24, 2017 | Last Updated: Jan 16, 2024 | Last Verified: Nov 05, 2024
张量是一种特殊的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。
Tensor类似于NumPy的ndarrays,不同之处是Tensor可以在GPU或其他专用硬件上运行以加速计算。如果你熟悉ndarrays,那么Tensor API会让你感觉得心应手。如果没有,请随着这个快速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)
从另一张量生成:
新的张量会保留参数张量的属性(形状、数据类型),除非显式覆盖。
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.1230, 0.3698],
[0.1598, 0.7721]])
使用随机或常量值生成:
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.2401, 0.5999, 0.7977],
[0.9621, 0.0340, 0.0267]])
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,可以通过编辑 > 笔记本设置分配一个GPU。
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
print(f"Device tensor is stored on: {tensor.device}")
Device tensor is stored on: cuda:0
试试列表中的一些操作。如果您熟悉 NumPy 的 API,那么使用张量 API 会非常轻松。
标准的 numpy 风格的索引和切片:
tensor = torch.ones(4, 4)
tensor[:,1] = 0
print(tensor)
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
连接张量 你可以使用``torch.cat``沿着给定维度连接一系列张量。另见`torch.stack <https://pytorch.org/docs/stable/generated/torch.stack.html>`__,这是与``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.]])
张量相乘
tensor.mul(tensor)
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
tensor * tensor
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
这会计算两个张量之间的矩阵乘法
tensor.matmul(tensor.T)
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
tensor @ tensor.T
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
就地操作 后缀为``_``的操作是就地进行的。例如: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.]])
备注
就地操作可以节省一些内存,但在计算导数时可能会有问题,因为会立即丢失历史记录。因此,不建议使用它们。
与 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 数组转张量¶
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.738 秒)