Tensor 数据类型
| Data type | dtype | CPU Tensor | GPU Tensor |
|---|---|---|---|
| Boolean | torch.bool | torch.BoolTensor | torch.cuda.BoolTensor |
| 8-bit integer (unsigned) | torch.uint8 | torch.ByteTensor | torch.cuda.ByteTensor |
| 8-bit integer (signed) | torch.int8 | torch.CharTensor | torch.cuda.CharTensor |
| 16-bit integer (signed) | torch.int16 or torch.short | torch.ShortTensor | torch.cuda.ShortTensor |
| 32-bit integer (signed) | torch.int32 or torch.int | torch.IntTensor | torch.cuda.IntTensor |
| 64-bit integer (signed) | torch.int64 or torch.long | torch.LongTensor | torch.cuda.LongTensor |
| 16-bit floating point | torch.float16 or torch.half | torch.HalfTensor | torch.cuda.HalfTensor |
| 16-bit floating point | torch.bfloat16 | torch.BFloat16Tensor | torch.cuda.BFloat16Tensor |
| 32-bit floating point | torch.float32 or torch.float | torch.FloatTensor | torch.cuda.FloatTensor |
| 64-bit floating point | torch.float64 or torch.double | torch.DoubleTensor | torch.cuda.DoubleTensor |
设置 Tensor 默认类型
1 | import torch |
set_default_dtype()只能设置floating-point类型,否则会报TypeError: only floating-point types are supported as the default type错误。
标量与张量
1 | import torch |
标量是一个单独的数,ndim为0。
创建 Tensor
.tensor
1 | import torch |
.from_numpy
1 | import numpy as np |
Tensor
1 | import torch |
Tensor支持两种传参方式:
- 当参数为列表时,创建列表对应维度的
Tensor并初始化数据为列表数据。 - 当参数不为列表时,与
.empty()类似,创建参数指定的shape的空的Tensor。
BoolTensor、ByteTensor、CharTensor、ShortTensor、IntTensor、LongTensor、HalfTensor、FloatTensor、DoubleTensor也是一样。
.empty/.zeros/.ones/.full/.eye
1 | import torch |
.arange/.linspace/.logspace
1 | import torch |
随机采样
随机种子
1 | import torch |
随机函数
.rand/.rand_like
1 | import torch |
torch.rand()返回在区间[0, 1)均匀分布的随机数填充的张量。
.randint/.randint_like
1 | import torch |
torch.randint(low, high)返回在区间[low, high)的随机数填充的张量。
.randperm
1 | import torch |
torch.randperm(n)返回在区间[0, n)的随机排列整数。
.randn/.randn_like
1 | import torch |
torch.randn()从标准正态分布中随机采样。
.normal
1 | import torch |
torch.normal(mean, std)从给定参数mean、std的离散正态分布中随机采样。
.bernoulli
1 | import torch |
torch.bernoulli()从伯努利分布中抽取二进制随机数(0 或 1)。输入的值必须在[0, 1]范围内。
.poisson
1 | import torch |
torch.poisson()从泊松分布中随机采样。
.multinomial
1 | import torch |
torch.multinomial(input, num_samples, replacement)对input的每一行做从多项式分布中采样num_samples次,输出的张量是每一次取值时input张量对应行的下标。
索引与切片
Python 语法
1 | import torch |
.narrow/.narrow_copy
1 | import torch |
torch.narrow()在指定维度缩小张量,可以简单理解为类似切片,tensor[start: start + length]
torch.narrow_copy()与torch.narrow()相同,但返回的是副本而不是共享存储。
.select/.index_select
1 | import torch |
torch.select()沿着维度dim,在给定索引index对input张量进行切片,等价于切片。比如:tensor.select(0, index)等于tensor[index]。tensor.select(2, index)等于tensor[:,:,index]。
torch.index_select()沿着维度dim对input张量进行索引。
.masked_select
1 | import torch |
torch.masked_select()根据布尔掩码选择数据,返回的是一维数据。
.gather
1 | import torch |
torch.gather(data, 0, index)对0维(行)进行tensor([[1, 0, 3, 2]]) 第 0 1 2 3 列索引:
[1][0] == 11
[0][1] == 15
[3][2] == 13
[2][3] == 8
加粗的是行索引的值1, 0, 3, 2,没加粗的为什么是0, 1, 2, 3呢?因为索引1是第0列,索引0是第1列,索引3是第2列,索引2是第3列。torch.gather(data, 0, index.t())对0维(行)进行tensor([[1], 第0列 [0], 第0列 [3], 第0列 [2]]) 第0列索引:
[1][0] == 11
[0][0] == 5
[3][0] == 10
[2][0] == 1
加粗的是行索引的值1, 0, 3, 2,没加粗的都是0,因为索引1, 0, 3, 2都是第0列。torch.gather(data, 1, index.t())对1维(列)进行tensor([[1], 第0行 [0], 第1行 [3], 第2行 [2]]) 第3行索引:
[0][1] == 15
[1][0] == 11
[2][3] == 8
[3][2] == 13
加粗的是列索引的值1, 0, 3, 2,没加粗的0, 1, 2, 3则是因为索引1是第0行,索引0是第1行,索引3是第2行,索引2是第3行。
.take/.take_along_dim
1 | import torch |
torch.take_along_dim()当dim=None时,等价于torch.take(),先把张量打平转成1维在根据索引获取元素。
当dim不等于None时,则与data.gather()相似。
.argwhere/.nonzero
1 | import torch |
torch.argwhere()和torch.nonzero()都是返回非0元素的索引。
当torch.nonzero()参数as_tuple=False时,效果与torch.argwhere()相同。
.where
1 | import torch |
.unravel_index
1 | import torch |
索引2在shape为(3, 3)的0行2列。
索引9可以理解为9 / prod(shape) == 9 % 9 == 0,所以在0行0列。
索引17可以理解为17 / prod(shape) == 17 % 9 == 8,所以在2行2列。
维度变换
.t/.transpose/.movedim/.permute
1 | import torch |
torch.t(input)只能处理维度小于等于2的,否则会报错。当维度是0或1维时,返回相同的结果,当维度为2时,等价于torch.transpose(input, 0, 1)
torch.transpose(input, dim0, dim1)一次只能操作两个维度,对调两个维度的位置。
torch.movedim(input, source, destination)将source维度移动到destination维度。
torch.permute(input, dims)一次可以操作多个维度,dims指定所有维度的顺序。在多维度操作上使用torch.permute()更直观。
torch.swapaxes()是torch.transpose()的别名。torch.swapdims()是torch.transpose()的别名。torch.moveaxis()是torch.movedim()的别名。
.view/.reshape
1 | import torch |
view()和reshape()都可以改变Tensor的维度,区别是:
view()只能对满足连续性的张量进行转换,当对不满足连续性的张量进行操作时会报RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.错误。transpose()和permute()会改变张量连续性,使用view()前需要先执行contiguous()。
reshape()则没有上述要求,可以直接使用,无需先执行contiguous()。
.squeeze/.unsqueeze
1 | import torch |
.expand/.repeat
1 | import torch |
.tile
1 | import torch |
合并与拆分
.cat
1 | import torch |
torch.concat()是torch.cat()的别名。torch.concatenate()是torch.cat()的别名。
.stack/.hstack/.vstack/.column_stack/.dstack
1 | import torch |
torch.hstack)按水平方向(列方向)依次堆叠张量。
torch.vstack)按垂直方向(行方向)依次堆叠张量。
torch.column_stack()除了张量是0维和1维外,等价于torch.hstack()。当张量t是0维或1维时,先reshape重塑为(t.numel(), 1)再水平堆叠。
torch.row_stack()是torch.vstack()的别名。
torch.dstack()在第3维度进行堆叠。
torch.stack()是一个更通用的函数,通过dim指定在任意维度进行堆叠,dim默认等于0。它总是增加一个新的维度来堆叠张量。
.chunk
1 | import torch |
.split/.hsplit/.vsplit/.dsplit/.tensor_split
1 | import torch |
torch.hsplit(input, indices_or_sections)当input是1维时,等价于torch.tensor_split(input, indices_or_sections, dim=0),当input是大于等于2维时,等价于torch.tensor_split(input, indices_or_sections, dim=1)。indices_or_sections如果是数字,必须能被整除,否则会抛出异常。
torch.vsplit(input, indices_or_sections)等价于torch.tensor_split(input, indices_or_sections, dim=0)。input必须大于等于2维。indices_or_sections如果是数字,必须能被整除,否则会抛出异常。
torch.dsplit(input, indices_or_sections)等价于torch.tensor_split(input, indices_or_sections, dim=2)。input必须大于等于3维。indices_or_sections如果是数字,必须能被整除,否则会抛出异常。
.unbind
1 | import torch |
逐点运算
.add/.sub/.mul/.div/.remainder/.fmod/.positive/.neg/.abs
1 | import torch |
torch.subtract()是torch.sub()的别名。torch.multiply()是torch.mul()的别名。torch.divide()是torch.div()的别名。torch.true_divide()是torch.div()在rounding_mode=None时的别名。torch.negative()是torch.neg()的别名。torch.absolute()是torch.abs()的别名。
在PyTorch 1.13后(含1.13),可以认为torch.floor_divide()是torch.div()在rounding_mode='floor'时的别名,效果是一样的。
.pow/.square/.sqrt/.rsqrt/.reciprocal
1 | import torch |
.exp/.log/.log2/.log10/.log1p
1 | import torch |
torch.log1p()计算input + 1的自然对数:。
.sin/.cos/.tan/.asin/.acos/.atan/.atan2/.sinh/.cosh/.tanh
1 | import torch |
torch.arcsin()是torch.asin()的别名。torch.arccos()是torch.acos()的别名。torch.arctan()是torch.atan()的别名。torch.arctan2()是torch.atan2()的别名。torch.arcsinh()是torch.asinh()的别名。torch.arccosh()是torch.acosh()的别名。torch.arctanh()是torch.atanh()的别名。
.angle/.deg2rad
1 | import numpy as np |
.bitwise_and/.bitwise_or/.bitwise_not/.bitwise_xor/.bitwise_left_shift/.bitwise_right_shift
1 | import torch |
.floor/.ceil/.round
1 | import torch |
torch.floor()向下取整,torch.ceil()向上取整,torch.round()四舍五入。
.trunc/.frac
1 | import torch |
torch.trunc()取整数,torch.frac()取小数。
torch.fix()是torch.trunc()的别名。
.clamp/.clamp_min/.clamp_max
1 | import torch |
torch.clamp()用于将输入的张量夹紧到区间[min, max]。
torch.clip()是torch.clamp()的别名。
.dot/.mm/.bmm/.matmul
1 | import torch |
dot()只支持一维矩阵相乘,mm()只支持二维矩阵相乘,bmm()只支持三维矩阵相乘,matmul()支持任意维度矩阵相乘。
比较运算
.eq/.ne/.gt/.ge/.lt/.le/.equal
1 | import torch |
torch.not_equal()是torch.ne()的别名。torch.greater()是torch.gt()的别名。torch.greater_equal()是torch.ge()的别名。torch.less()是torch.lt()的别名。torch.less_equal()是torch.le()的别名。
.isfinite/.isinf/.isposinf/.isneginf/.isnan/.isreal/.isin
1 | import torch |
.isclose/.allclose
1 | import torch |
torch.isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False)
torch.allclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False)
校验是否接近公式:
.maximum/.minimum/.fmax/.fmin
1 | import torch |
torch.maximum()和torch.minimum()用于比较两数的大小,不支持比较NaN。
torch.fmax()和torch.fmin()用于比较两数的大小,支持比较NaN。
.sort/.msort/.argsort
1 | import torch |
torch.sort()排序后返回排序结果和索引。
torch.msort(input))等价于torch.sort()对第一维度进行排序在取排序结果,torch.sort(input, dim=0)[0],返回结果不包含索引。
torch.argsort()返回排序后的索引。
.topk/.kthvalue
1 | import torch |
torch.topk()获取前k大的数据,torch.kthvalue()获取第k小的数据。
归约运算
.max/.min/.amax/.amin/.aminmax/.argmax/.argmin
1 | import torch |
torch.max()和torch.min()指定了dim时,返回极值和索引。
torch.amax()和torch.amin()只返回极值,不返回索引。
torch.argmax()和torch.argmin()返回极值对应的索引。不指定dim时,返回的是打平后的索引。
.mean/.nanmean
1 | import torch |
.median/.nanmedian
1 | import torch |
.sum/.nansum
1 | import torch |
.prod
1 | import torch |
.var/.var_mean/.std/.std_mean
1 | import torch |
总体方差:
样本方差:
总体标准差:
样本标准差:
.norm
1 | import torch |
一范数:
二范数:
p范数:
.dist
1 | import torch |
torch.dist()返回(input - other)的p范数。
.any/.all
1 | import torch |
序列化
.save
1 | import io |
.load
1 | import io |