翻译文章链接:https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html

1、张量是一种特殊的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。张量类似于NumPy 的ndarray,除了张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存,从而无需复制数据

2、首先,导入所需用的python库,代码如下:

import torch
import numpy as np

如果没安装,可执行一下命令,安装:

pip install torchvision

3、张量的初始化,张量可以以各种方式初始化。
(1)、直接从数据,张量可以直接从数据中创建。数据类型是自动推断的。示例如下:

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

如下图所示:

pytorch 三维张量 方差 pytorch中的张量_数组


(2)、来自 NumPy 数组,张量可以从 NumPy 数组创建。示例如下:

np_array = np.array(data)
x_np = torch.from_numpy(np_array)
print(x_np)

如下图所示:

pytorch 三维张量 方差 pytorch中的张量_PyTorch张量学习_02


(3)、从另一个张量:新张量保留参数张量的属性(形状、数据类型),除非显式覆盖。

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.9805, 0.0968],
        [0.0682, 0.8428]])

(4)、使用随机或恒定值: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.0501, 0.6421, 0.9623],
        [0.2208, 0.8159, 0.6055]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

4、张量的属性,张量属性描述了它们的形状、数据类型和存储它们的设备。代码示例如下:

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

5、张量的运算,其中有100 多种张量运算,包括算术、线性代数、矩阵操作(转置、索引、切片)、采样等,这些操作中的每一个都可以在 GPU 上运行(通常以比 CPU 更高的速度)。
(1)、默认情况下,张量是在 CPU 上创建的。我们需要使用 .to方法明确地将张量移动到 GPU(在检查 GPU 可用性之后)。请记住,跨设备复制大张量在时间和内存方面可能会很昂贵!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to("cuda")

(2)、标准的类似 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.]])

(3)、连接张量,可以用来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.]])

(4)、算术运算

示例代码1,这将计算两个张量之间的矩阵乘法。y1、y2、y3将具有相同的值

y1 = tensor @ tensor.T
print(y1)
y2 = tensor.matmul(tensor.T)
print(y2)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
print(y3)

输出都是一样的:

tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

示例代码2,这将计算元素的乘积。z1、z2、z3将具有相同的值

z1 = tensor * tensor
print(z1)
z2 = tensor.mul(tensor)
print(z2)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
print(z3)

输出都是一样的:

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

(5)、单元素张量,例如通过将张量的所有值聚合为一个值,您可以使用以下方法将其转换为 Python 数值item(),示例代码如下:

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))

输出如下:

12.0 <class 'float'>

(6)、就地操作,将结果存储到操作数中的操作称为就地操作。它们由_后缀表示。例如:x.copy_(y), x.t_(), 会变x。示例代码如下:

print(f"{tensor} \n")
# 各个数值减去1
tensor.subtract_(1)
print(tensor)
# 各个数值加上5
tensor.add_(5)
print(tensor)

输出如下:

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[ 0., -1.,  0.,  0.],
        [ 0., -1.,  0.,  0.],
        [ 0., -1.,  0.,  0.],
        [ 0., -1.,  0.,  0.]])

tensor([[5., 4., 5., 5.],
        [5., 4., 5., 5.],
        [5., 4., 5., 5.],
        [5., 4., 5., 5.]])

注:就地操作可以节省一些内存,但在计算导数时可能会出现问题,因为会立即丢失历史记录。因此,不鼓励使用它们。

6、与 NumPy 桥接,CPU 和 NumPy 数组上的张量可以共享它们的底层内存位置,改变一个会改变另一个。
(1)、张量到 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.subtract_(1)
print(f"t: {t}")
print(f"n: {n}")

输出如下,可看到张量减1之后,对应的numpy也发生了变化:

t:tensor([0., 0., 0., 0., 0.])
n:[0. 0. 0. 0. 0.]

(2)、NumPy 数组到张量

n = np.ones(5)
print(n)
t = torch.from_numpy(n)
print(t)

输出如下:

[1. 1. 1. 1. 1.]
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)

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.]