(2)PyTorch之Tensor

546 阅读4分钟

一、简介

  PyTorch里面处理的最基本的操作对象就是Tensor(张量),表示的是一个多维的矩阵,比如零维就是一个点,一维就是向量,二维就是一个矩阵,多维就相当于一个多维的数组,这和numpy是对应的,而且PyTorch的Tensor可以和numpy的ndarray相互转换,唯一不同的是PyTorch可以在GPU上运行,而numpy的ndarray只能在CPU上运行。

1.jpg

二、类型

Torch 定义了 10 种具有 CPU 和 GPU 变体的张量类型,如下所示:

数据类型dtypeCPU tensorGPU tensor
32-bit floating pointtorch.float32 or torch.floattorch.FloatTensortorch.cuda.FloatTensor
64-bit floating pointtorch.float64 or torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor
16-bit floating point 1torch.float16 or torch.halftorch.HalfTensortorch.cuda.HalfTensor
16-bit floating point 2torch.bfloat16torch.BFloat16Tensortorch.cuda.BFloat16Tensor
32-bit complextorch.complex32
64-bit complextorch.complex64
128-bit complextorch.complex128 or torch.cdouble
8-bit integer (unsigned)torch.uint8torch.ByteTensortorch.cuda.ByteTensor
8-bit integer (signed)torch.int8torch.CharTensortorch.cuda.CharTensor
16-bit integer (signed)torch.int16 or torch.shorttorch.ShortTensortorch.cuda.ShortTensor
32-bit integer (signed)torch.int32 or torch.inttorch.IntTensortorch.cuda.IntTensor
64-bit integer (signed)torch.int64 or torch.longtorch.LongTensortorch.cuda.LongTensor
Booleantorch.booltorch.BoolTensortorch.cuda.BoolTensor
quantized 8-bit integer (unsigned)torch.quint8torch.ByteTensor/
quantized 8-bit integer (signed)torch.qint8torch.CharTensor/
quantized 32-bit integer (signed)torch.qfint32torch.IntTensor/
quantized 4-bit integer (unsigned) 3torch.quint4x2torch.ByteTensor/

torch.Tensor是默认的tensor类型(torch.FlaotTensor)的简称。

其类间的继承关系如下:

class DoubleTensor(Tensor): ...
class FloatTensor(Tensor): ...
class LongTensor(Tensor): ...
class IntTensor(Tensor): ...
class ShortTensor(Tensor): ...
class HalfTensor(Tensor): ...
class CharTensor(Tensor): ...
class ByteTensor(Tensor): ...
class BoolTensor(Tensor): ...

三、常用操作

创建

典型的tensor构建方法:

torch.tensor(data, dtype=None, device=None, requires_grad=False) (?)

1.png

默认dtype为torch.float32

从其他形式转换而来:

torch.as_tensor(data, dtype=None, device=None) (?)
torch.from_numpy(ndarray) (?)

创建特殊值组成的tensor:

torch.zeros(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)
torch.zeros_like(input, dtype=None, layout=None, device=None, requires_grad=False) (?)
torch.ones(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)
torch.ones_like(input, dtype=None, layout=None, device=None, requires_grad=False) (?)
torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)
torch.empty(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)
torch.empty_like(input, dtype=None, layout=None, device=None, requires_grad=False) (?)
torch.full(size, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)
torch.full_like(input, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)

按照步长或者区间创建tensor

torch.arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)
torch.linspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)
torch.logspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) (?)

索引,分块,组合,变形

组合

torch.cat(seq, dim=0, out=None):按照已经存在的维度进行concatenate。(?)
torch.stack(seq, dim=0, out=None):按照新的维度进行concatenate。(?)

分块

torch.chunk(tensor, chunks, dim=0):按照某个维度平均分块(最后一个可能小于平均值)(?)
torch.split(tensor, split_size_or_sections, dim=0):按照某个维度依照第二个参数给出的list或者int进行分割tensor。(?)

索引

torch.gather(input, dim, index, out=None):在指定维度上按照索引赋值输出tensor。输入与输出大小一致。(?)
torch.index_select(input, dim, index, out=None):选出一维度的一些slice组合成新的tensor。指定维度的大小与index大小一致。(?)
torch.masked_select(input, mask, out=None):按照mask输出一个一维的tensor。(?)
torch.take(input, indices):将输入看成1D tensor,按照索引得到输出。输出大小与index大小一致。(?)
torch.nonzero(input, out=None):输出非0 元素的坐标。(?)
torch.where(condition, x, y):按照条件从x和y中选出满足条件的元素组成新的tensor。(?)

变形

torch.reshape(input, shape) (?)
torch.t(input): 只针对2D tensor转置 (?)
torch.transpose(input, dim0, dim1):交换两个维度 (?)
torch.squeeze(input, dim=None, out=None):去除那些维度大小为1的维度 (?)
torch.unbind(tensor, dim=0):去除某个维度 (?)
torch.unsqueeze(input, dim, out=None):在指定位置添加维度。 (?)

数学运算

Pointwise Ops 网格操作

torch.addcdiv(tensor, value=1, tensor1, tensor2, out=None)
outi=inputi+valuetensor1itensor2iout_i = input_i + value * \frac{tensor1_i}{tensor2_i} (?)

torch.addcmul(tensor, value=1, tensor1, tensor2, out=None)
outi=inputi+valuetensor1itensor2iout_i = input_i + value * tensor1_i * tensor2_i (?)

torch.ceil(input, out=None) (?)

torch.clamp(input, min, max, out=None) :max 或者min 可以用 * 代替,表示没有该项限制,把所有元素转换到[min, max]范围内
yi=min(max(xi,min_valuei),max_valuei)y_i = min(max(x_i, min\_value_i),max\_value_i) (?)

torch.erf(tensor, out=None) (?)

torch.fmod(input, divisor, out=None): 计算余数 (?)

torch.frac(tensor, out=None) 计算每个元素小数部分
outi=inputi  inputi  sgn(inputi)out_i = input_i\ −\ ⌊∣inputi​∣⌋\ ∗\ sgn(inputi​) (?)

torch.lerp(start, end, weight, out=None) 对两个张量进行线性插值
outi=starti+weighti×(endistarti)out_i=start_i+weight_i×(end_i−start_i) (?)

torch.neg(input, out=None) 对每个元素取负数
out=1×inputout=−1×input (?)

torch.pow(base, input, out=None) 对每个元素取指数
outi=xiexponentout_i=x_i^{exponent} (?)

torch.reciprocal(input, out=None) 对每个元素取倒数
outi=1inputiout_i=\frac{1}{input_i} (?)

torch.remainder(input, divisor, out=None):计算余数 (?)

torch.rsqrt(input, out=None) 取每个元素的平方根的倒数
outi=1inputiout_i=\frac{1}{\sqrt {input_i}} (?)

torch.sign(input, out=None) :取符号
outi=sgn(inputi)out_i=sgn(input_i) (?)

torch.trunc(input, out=None):截取整数部分 (?)

Reduction Ops

torch.dist(input, other, p=2) 计算p范数 (?)

torch.norm() 计算2范数 (?)

torch.prod() 计算所有元素的积 (?)

torch.unique(input, sorted=False, return_inverse=False) 以1D向量保存张量中不同的元素。 (?)

Comparison Ops

torch.isfinite(tensor) 
torch.isinf(tensor) 
torch.isnan(tensor)

返回一个标记元素是否为 finite(有限)/inf(无限)/nan(不是数字) 的mask 张量。

torch.kthvalue(input, k, dim=None, keepdim=False, out=None) -> (Tensor, LongTensor) 返回最小的第k个元素,如果为指定维度,则默认为最后一个维度。 (?)

torch.sort(input, dim=None, descending=False, out=None) 沿着某一维度对张量进行升序排列。 (?)

torch.topk(input, k, dim=None, largest=True, sorted=True, out=None) 返回最大的k个元素。 (?)

Other Operations

torch.bincount(self, weights=None, minlength=0) 返回每个值得频数。 (?) numpy.bincount详解

torch.cross(input, other, dim=-1, out=None) 按照维度计算叉积。 (?)

torch.diag(input, diagonal=0, out=None) 如果输入时1D,则返回一个相应的对角矩阵;如果输入时2D,则返回相应对角线的元素。 (?)

torch.flip(input, dims) 按照给定维度翻转张量 (?)

torch.histc(input, bins=100, min=0, max=0, out=None) 计算张量的直方图。 (?)

torch.meshgrid(seq) 生成网格(可以生成坐标)。 (?)