What is Tensor?
Tensor:一个多维数组,是标量、向量、矩阵的高维拓展,通常一维的张量就是我们所谓的向量,二维的张量就是我们所谓的矩阵,再往后拓展多维的我们就称之为张量。
Torch工具包
import torch :张量的有关运算。如创建、索引、连接、转置、加减乘除、切片等
1.创建:
(1)
torch.tensor()
功能:从data创建tensor
• data: 数据, 可以是list, numpy
• dtype : 数据类型,默认与data的一致
• device : 所在设备, cuda/cpu
• requires_grad:是否需要梯度
• pin_memory:是否存于锁页内存
(2)
还可以按照数值创建:
torch.zeros()
功能:依size创建全0张量
• size: 张量的形状, 如(3, 3)、(3, 224,224)
• out : 输出的张量
• layout : 内存中布局形式, 有strided,sparse_coo等
(3)
还可以创建单位对角矩阵:
torch.eye(n,m=None,out=None,dtype=None,layout=torch.strided,device=None,requires_grad=False)
功能:创建单位对角矩阵。注意:默认为方阵
• n: 矩阵行数
• m : 矩阵列数
(4)
torch.normal(mean,std,out=None)
功能:生成正态分布(高斯分布)
• mean : 均值
• std : 标准差
(5)
torch.randn(*size,out=None,dtype=None,layout=torch.strided,device=None,requires_grad=False)
功能:生成标准正态分布
• size : 张量的形状
2.连接
torch.cat(tensors,
dim=0,
out=None)
功能:将张量按维度dim进行拼接
• tensors: 张量序列
• dim : 要拼接的维度
torch.stack(tensors,
dim=0,
out=None)
功能:在新创建的维度dim上进行拼接
• tensors:张量序列
• dim :要拼接的维度
3.切分
torch.chunk(input,
chunks,
dim=0)
功能:将张量按维度dim进行平均切分,返回张量列表。若不能整除,最后一份张量小于其他张量
• input: 要切分的张量
• chunks : 要切分的份数
• dim : 要切分的维度
torch.split(tensor,
split_size_or_sections,
dim=0)
功能:将张量按维度dim进行切分,返回张量列表
• tensor: 要切分的张量
• split_size_or_sections : 为int时,表示每一份的长度;为list时,按list元素切分
• dim : 要切分的维度
4.索引
torch.index_select(input,
dim,
index,
out=None)
功能:在维度dim上,按index索引数据
• input: 要索引的张量
• dim: 要索引的维度
• index : 要索引数据的序号
5.变换
torch.reshape(input,
shape)
功能:变换张量形状
• input: 要变换的张量
• shape: 新张量的形状
torch.transpose(input,
dim0,
dim1)
功能:交换张量的两个维度
• input: 要变换的张量
• dim0: 要交换的维度
• dim1: 要交换的维度
6.转置
torch.t(input)
7.压缩
torch.squeeze(input,
dim=None,
out=None)
功能:压缩长度为1的维度(轴)
• dim: 若为None,移除所有长度为1的轴;若指定维度,当且仅当该轴长度为1时,可以被移除;
torch.usqueeze(input,
dim,
out=None)
功能:依据dim扩展维度
• dim: 扩展的维度
8.加减乘除等运算
加减乘除:
torch.add()
torch.addcdiv()
torch.addcmul()
torch.sub()
torch.div()
torch.mul()
对数,指数,幂指数:
torch.log(input, out=None)
torch.log10(input, out=None)
torch.log2(input, out=None)
torch.exp(input, out=None)
torch.pow()
三角函数:
torch.abs(input, out=None)
torch.acos(input, out=None)
torch.cosh(input, out=None)
torch.cos(input, out=None)
torch.asin(input, out=None)
torch.atan(input, out=None)
torch.atan2(input, other, out=None)