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
torch.rand(*size, out=None) -> Tensor
返回一个张量,包含从区间[0,1)的均匀分布中抽取的一组随机数,形状由可变参数size(int...)
决定。
- 例子
>>> torch.rand(2, 3)
tensor([[0.1183, 0.5954, 0.0256],
[0.1915, 0.2350, 0.4634]])
>>> torch.rand(4)
tensor([0.4275, 0.2355, 0.1684, 0.3253])
- 与
torch.rand
相似的是torch.randn
,不同之处是张量包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取一组随机数
torch.zeros
torch.zeros(*sizes, out=None) → Tensor
返回一个全为标量0的张量,形状由sizes(int...)
定义
- 例子
>>> torch.zeros(3, 4)
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
torch.gather
torch.gather(input, dim, index, out=None) → Tensor
沿给定轴dim
,将输入索引张量index
指定位置的值进行聚合
对于一个3维张量,输出可以定义为:
out[i][j][k] = tensor[index[i][j][k]][j][k] # dim=0
out[i][j][k] = tensor[i][index[i][j][k]][k] # dim=1
out[i][j][k] = tensor[i][j][index[i][j][k]] # dim=3
- 例子
>>> torch.gather(t, 1, torch.LongTensor([[0, 0],[1, 0]]))
tensor([[1., 1.],
[4., 3.]])
- 过程图示(刚开始接触,确实很难理解。。。。)
torch.view
表示将原矩阵转化成i
行j
列的形式,i
为-1表示不限制行数,j
为-1表示不限制列数
- 例子