python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > PyTorch torch包

PyTorch使用教程中的torch包详解

作者:深图智能

文章介绍了PyTorch框架中torch包的基础组件,包括张量的创建和基本操作、张量的保存和加载、随机数生成以及张量的基础数学运算,感兴趣的朋友跟随小编一起看看吧

1、简介

torch包是PyTorch框架最外层的包,主要是包含了张量的创建和基本操作、随机数生成器、序列化、局部梯度操作的上下文管理器等等,内容很多。我们基础学习的时候,只有关注张量的创建、序列化,随机数、张量的数学数学计算等常用的点即可。

2、什么是张量

在PyTorch中,张量(Tensor)是一个核心概念,它是深度学习和科学计算的基础数据结构。在PyTorch的整个计算过程中,所有的数据结构都是以张量的形式表现。例如输入的图像、标签,输出的结构等,最终都是以张量的形式进入PyTorch的计算图。

3、torch包的张量操作

3.1 张量创建

1. 创建全0的张量

torch.zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

参数

size (int…) – 定义输出张量形状的整数序列。可以是可变数量的参数或类似列表或元组的集合。

示例

>>> torch.zeros(2, 3)
tensor([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])
>>> torch.zeros(5)
tensor([ 0.,  0.,  0.,  0.,  0.])

2. 创建全1的张量

torch.ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

参数

size (int…) – 定义输出张量形状的一系列整数。可以是可变数量的参数或类似列表或元组的集合。

示例

>>> torch.ones(2, 3)
tensor([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.]])
>>> torch.ones(5)
tensor([ 1.,  1.,  1.,  1.,  1.])

3. 创建未初始化数据的张量

torch.empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) → Tensor

参数

size (int…) – 定义输出张量形状的整数序列。可以是可变数量的参数或集合,如列表或元组。

示例

>>> torch.empty((2,3), dtype=torch.int64)
tensor([[ 9.4064e+13,  2.8000e+01,  9.3493e+13],
        [ 7.5751e+18,  7.1428e+18,  7.5955e+18]])

4. 创建对角线上的元素为1的二维张量

torch.eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

参数

n (int) – 行数

示例

>>> torch.eye(3)
tensor([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]])

5. 创建填充指定值的张量

torch.full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

参数

示例

>>> torch.full((2, 3), 3.141592)
tensor([[ 3.1416,  3.1416,  3.1416],
        [ 3.1416,  3.1416,  3.1416]])

6. 从NumPy 数组创建的张量:from_numpy
示例

>>> a = numpy.array([1, 2, 3])
>>> t = torch.from_numpy(a)
>>> t
tensor([ 1,  2,  3])
>>> t[0] = -1
>>> a
array([-1,  2,  3])

7. 判断一个Obj是不是张量:is_tensor
示例

>>> x = torch.tensor([1, 2, 3])
>>> torch.is_tensor(x)
True

3.2 张量操作

1. reshape操作

torch.reshape(input, shape) → Tensor

参数

示例

>>> a = torch.arange(4.)
>>> torch.reshape(a, (2, 2))
tensor([[ 0.,  1.],
        [ 2.,  3.]])
>>> b = torch.tensor([[0, 1], [2, 3]])
>>> torch.reshape(b, (-1,))
tensor([ 0,  1,  2,  3])

2. cat操作
在给定的维度上连接给定的张量序列。所有张量必须具有相同的形状(连接维度除外),或者是一个大小为 (0,) 的一维空张量。

torch.cat(tensors, dim=0, *, out=None) → Tensor

参数

示例

>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 0)
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 1)
tensor([[ 0.6580, -1.0969, -0.4614,  0.6580, -1.0969, -0.4614,  0.6580,
         -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497, -0.1034, -0.5790,  0.1497, -0.1034,
         -0.5790,  0.1497]])

3. squeeze操作
返回一个张量,其中所有指定维度的 input 大小为 1 的维度都被移除。

torch.squeeze(input, dim=None) → Tensor

示例

>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x)
>>> y.size()
torch.Size([2, 2, 2])
>>> y = torch.squeeze(x, 0)
>>> y.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 2, 1, 2])
>>> y = torch.squeeze(x, (1, 2, 3))
torch.Size([2, 2, 2])

4、 随机数

4.1随机数发生器配置

1. seed操作
将所有设备上生成随机数的种子设置为非确定性随机数。返回用于为 RNG 播种的 64 位数字。
示例

>>> torch.seed()
269874079427000

2. 手动设置随机数的种子值:manual_seed
设置所有设备上生成随机数的种子。
示例

>>> torch.manual_seed(torch.seed())
<torch._C.Generator object at 0x0000022952198270>

4.2 创建随机张量

1. torch.rand
创建一个张量,其中填充了来自 [0,1) 区间上的均匀分布的随机数。

torch.rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor

参数

size (int…) – 定义输出张量形状的整数序列。可以是可变数量的参数或像列表或元组这样的集合。

示例

>>> torch.rand(4)
tensor([ 0.5204,  0.2503,  0.3525,  0.5673])
>>> torch.rand(2, 3)
tensor([[ 0.8237,  0.5781,  0.6879],
        [ 0.3816,  0.7249,  0.0998]])

2. randint
创建一个张量,其中填充了在 low(包含)和 high(不包含)之间均匀生成的随机整数。

torch.randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

参数

示例

>>> torch.randint(3, 5, (3,))
tensor([4, 3, 4])
>>> torch.randint(10, (2, 2))
tensor([[0, 2],
        [5, 5]])
>>> torch.randint(3, 10, (2, 2))
tensor([[4, 5],
        [6, 7]])

5、张量的保存和加载

1. 保存
将张量保存到磁盘文件。

torch.save(obj, f, pickle_module=pickle, pickle_protocol=DEFAULT_PROTOCOL, _use_new_zipfile_serialization=True)

PyTorch 的常见约定是使用 .pt 文件扩展名保存张量。

参数

示例

>>> x = torch.tensor([0, 1, 2, 3, 4])
>>> torch.save(x, "tensor.pt")

2. 加载
从文件中加载使用 torch.save() 保存的对象。

torch.load(f, map_location=None, pickle_module=pickle, *, weights_only=False, mmap=None, **pickle_load_args)

参数

当在包含 GPU 张量文件上调用torch.load()时,默认情况下,这些张量将加载到 GPU。可以调用torch.load(…, map_location=‘cpu’),然后load_state_dict()来避免在加载模型检查时出现 GPU 内存激增。

load函数的用法较多,可以通过pick_module参数传入自定义的序列化和反序列化的模块,可以通过字节流、文件对象等进行张量加载。详细的用法可以访问官网的API文档进行查看:https://pytorch.ac.cn/docs/stable/generated/torch.load.html#torch.load。

示例

# 加载张量至CPU
>>> torch.load("tensors.pt", map_location=torch.device("cpu"), weights_only=True)
# 加载张量至 GPU 1
>>> torch.load(
...     "tensors.pt",
...     map_location=lambda storage, loc: storage.cuda(1),
...     weights_only=True,
... )  # type: ignore[attr-defined]

6、张量的基础数学计算

张量的数学计算部分主要是包含了逐元素的线性计算、统计信息计算、比较操作、FFT相关的频域操作等等。

1. 绝对值

torch.abs(input, *, out=None) → Tensor

示例

>>> torch.abs(torch.tensor([-1, -2, 3]))
tensor([ 1,  2,  3])

2. 三角函数相关
cos、acos、sin、asin、tan、atan、atan2等等。
示例

>>> a = torch.randn(4)
>>> a
tensor([-0.5461,  0.1347, -2.7266, -0.2746])
>>> torch.sin(a)
tensor([-0.5194,  0.1343, -0.4032, -0.2711])

3. 统计信息相关
和值sum、均值标准差std_mean、中值median、最大值max、最小值min等等。

>>> a = torch.tensor(
...     [[ 0.2035,  1.2959,  1.8101, -0.4644],
...      [ 1.5027, -0.3270,  0.5905,  0.6538],
...      [-1.5745,  1.3330, -0.5596, -0.6548],
...      [ 0.1264, -0.5080,  1.6420,  0.1992]])
>>> torch.std_mean(a, dim=0, keepdim=True)
(tensor([[1.2620, 1.0028, 1.0957, 0.6038]]),
 tensor([[ 0.0645,  0.4485,  0.8707, -0.0665]]))

7、小结

主要介绍了PyTorch框架中torch包的常用组件,包含张量的创建和基本操作、张量的保存和加载以及随机数、张量的基础数学运算等相关操作。

到此这篇关于PyTorch使用教程中的torch包详解的文章就介绍到这了,更多相关PyTorch torch包内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文