Torch
pytorch深度学习框架最重要的包torch
相关介绍
torch
官方文档说明如下:
The torch package contains data structures for multi-dimensional tensors and defines mathematical operations over these tensors. Additionally, it provides many utilities for efficient serializing of Tensors and arbitrary types, and other useful utilities.
句句不离tensor
,可知torch
是包含了多维张量的数据结构以及对张量的多种数学操作,还提供了更加有效地对张量和任意类型进行序列化的工具。
基本操作
简单介绍几个目前自己看项目看到的。之后会补充
torch.rand
返回一个张量,包含从区间[0,1)的均匀分布中抽取的一组随机数,形状由可变参数size(int...)
决定。
- 例子
- 与
torch.rand
相似的是torch.randn
,不同之处是张量包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取一组随机数
torch.zeros
返回一个全为标量0的张量,形状由sizes(int...)
定义
- 例子
torch.gather
沿给定轴dim
,将输入索引张量index
指定位置的值进行聚合
对于一个3维张量,输出可以定义为:
- 例子
- 过程图示(刚开始接触,确实很难理解。。。。)
torch.view
表示将原矩阵转化成i
行j
列的形式,i
为-1表示不限制行数,j
为-1表示不限制列数
- 例子
torch.squeeze
将输入张量形状中的1
去除并返回。
如果输入的形如(A×1×B×1×C×1×D),那么输出形状就为(A×B×C×D)
当给定维度dim
时,挤压操作只在给定的维度上。
如果输入形状为(A×1×B),dim = 1
那么输出形状为(A×B)
一句话来说,如果不给定dim,则把input的所有size为1的维度给移除;如果给定dim,则只移除给定的且size为1的维度。
- 例子
torch.unsqueeze
返回一个新张量,对输入的指定位置插入维度1
如果dim
为负,则将会被转化为 dim + input.dim() + 1
torch.max/min
1、返回输入tensor中所有元素的最大值
- 例子
2、按维度dim返回最大值,并且返回最大值的索引
返回的最大值和索引各是一个tensor,一起构成元组(Tensor,LongTensor)
。。。。。