官网链接
https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html
张量
张量是一种特殊的数据结构,与数组和矩阵非常相似。在PyTorch中,我们使用张量来编码模型的输入和输出,以及模型的参数。
张量类似于NumPy中的ndarray,除了张量可以在gpu或其他硬件加速器上运行。事实上,张量和NumPy数组通常可以共享相同的底层内存,从而消除了复制数据的需要(参见 Bridge with NumPy)。张量还针对自动微分进行了优化(稍后我们将在Autograd 一节中看到更多相关内容)。如果您熟悉ndarray,那么您将对Tensor API非常熟悉。如果没有,跟着做!
import torch
import numpy as np
初始化张量
张量可以用不同的方式初始化。看下面的这些例子:
通过数据初始化
张量可以直接从数据中创建。自动推断数据类型。
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.3272, 0.0090],
[0.7144, 0.0619]])
通过随机或指定值初始化
形状是张量维度的元组,在下面的函数中,它决定了输出张量的维度。
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.2801, 0.1581, 0.3181],
[0.4325, 0.7844, 0.0716]])
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多种张量运算操作,包括算术,线性代数,矩阵操作(转置,索引,切片),采样和更多的全面描述在这里(here)
这些操作都可以在GPU上运行(通常比在CPU上运行速度更快)。如果你使用的是Colab,通过运行时分配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-索引和切片:
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 沿着给定的维数串联张量序列 来连接张量。参见torch.stack, 另一个张量连接算子,与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)
print(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)
print(torch.mul(tensor, tensor, out=z3))
输出
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
Single-element tensors,如果你有一个元素的张量,例如通过将一个张量的所有值聚合为一个值,你可以使用item()将其转换为Python数值:
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
输出
12.0 <class 'float'>
In-place 操作,将结果存储到操作数中的操作称为In-place调用。它们用后缀_表示。例如: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.]])
注意
In-place操作可以节省一些内存,但是在计算衍生品时可能会出现问题,因为会立即丢失历史记录。因此,不鼓励使用它们。
与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.]