【PyTorch攻略(1/7)】 张量基本语法-LMLPHP

一、说明

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

        张量类似于 NumPy 和 ndarray,除了张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存地址,具有称为桥接到 np 标签的功能,这消除了复制数据的需要。张量也针对自动微分进行了优化。如果你熟悉ndarrays,那么你就可以熟悉Tensor API。如果没有,请跟着走!

        让我们从设置环境开始。

%matplotlib inline
import torch
import numpy as np

二、初始化张量

张量可以通过多种方式初始化。例如:

  • 直接从数据
data = [[1,2], [3,4]]
x_data = torch.tensor(data)
  • 从数字派数组

        张量可以从 NumPy 数组创建,反之亦然。由于 numpy 'np_array' 和张量 'x_np' 共享相同的内存位置,因此更改其中一个的值将影响另一个。

np_array = np.array
x_np = torch.from_numpy(np_array)
  • 从另一个张量
x_ones = torch.ones_like(x_data)
x_rand = torch.rand_like(x_data, dtype = torch.float)
  • 使用随机值或常量值

        在下面的函数中,它确定输出张量的维数。形状是张量维度的元组。它显示了张量中的行数和列数,例如,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.4424, 0.4927, 0.5646],
        [0.7742, 0.0868, 0.3927]]) 

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

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

2.1 张量的属性

张量属性描述了它的形状、数据类型以及存储它们的设备。

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

        T这里有 100 多种张量运算,包括算术、线性代数、矩阵操作(转置、索引、切片)。这些操作中的每一个都可以在 GPU 上运行。

  • CPU 最多有 16 个内核。核心是执行实际计算的单元。每个核心按顺序处理任务(一次一个任务)。
  • GPU 有 1000 个内核。GPU 内核以并行处理方式处理计算。任务在不同的内核之间划分和处理。这就是在大多数情况下使GPU比CPU更快的原因。GPU 处理大数据的性能优于处理小数据。GPU 通常用于图形或神经网络的高强度计算。

        默认情况下,张量是在 CPU 上创建的。张量也可以计算到 GPU;为此,您需要使用 .to 方法移动它们(在检查 GPU 可用性之后)。

if torch.cuda.is_available():
  tensor = tensor.to('cuda')

2.2 索引和切片张量

tensor = torch.ones(4,4)
print('First row: ', tensor[0])
print('First column: ', tensor[:, 0])
print('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.]])

2.3 连接张量

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

        您可以使用 torch.cat 沿给定维度连接一系列张量。torch.stack是另一个与 torch.cat 略有不同的张量连接选项。

2.4 算术运算

# This computes the matrix multiplication between two tensors. 
# y1, y2, y3 have the same value
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

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

# This computes the element-wise product. 
# z1, z2, z3 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.]])

2.5 单元素张量

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

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


2.6 就地操作

print(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.]])

        将结果存储到操作数中的操作称为就地操作。它们由 _ 后缀表示。例如:x.copy_(y)、x.t_() 将更改 x。

2.7 张量到 NumPy 数组

t = torch.ones(5)
n = t.numpy()
print(f"t: {t}")
print(f"n: {n}")

# A change in tensor reflects in the NumPy array.
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

2.8 NumPy 数组到张量

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

# A change in Numpy array reflects in the tensor.
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.]

下一>> PyTorch 简介 (2/7)

09-19 06:34