张量的操作

一、张量的拼接

1、torch.cat(input, dim=0, out=None)
功能:将张量按维度dim进行拼接
参数:input:要操作的张量
dim:要拼接的维度
2、torch.stack(input, dim=0, out=None)
功能:在新创建的维度上进行拼接
参数:input:要操作的张量
dim:要拼接的维度
cat和stack的区别是,cat方法不会扩展维度,而stack会扩展一个新的维度进行拼接

二、张量的切分

1、torch.chunk(input, chunks, dim=0)
功能:将张量按维度进行平均切分
返回值:张量列表
注意:若不能整除,最后一份的张量小于其他张量
参数:input:要操作的张量
chunks:要切分的份数
dim:维度
2、torch.split(input, split_size_or_sections, dim=0)
功能:将张量按维度进行切分
返回值:张量列表
参数:input:要切分的张量
split_size_or_sections:为int时,表示每一份的长度,为list时,按list元素切分
dim:维度
注意:split_size_or_sections在使用int时等于torch.chunk,在使用list时list内各元素之和要等于这个维度上长度(不等于就会报错)

三、张量的索引

1、torch.index_select(input, dim, index, out=None)
功能:在维度上,按index索引数据
返回值:索引到的所有数据拼接成新的张量输出
参数:input:要操作的张量
dim:维度
index:要索引的序号,索引的数据类型必须是torch.long
2、torch.masked_select(input, mask, out=None)
功能:按照mask中的True进行索引
返回值::一维张量
参数:input:要操作的张量
mask:与input相同的布尔类型的张量

四、张量的变换

1、torch.reshape(input, shape)
功能:变换张量的形状
注意:当张量在内存中连续时,新张量与input共享数据内存
参数:input:要操作的张量
shape:新张量的形状
2、torch.transpose(input, dim0, dim1)
功能:交换张量的两个维度
参数:input:要操作的张量
dim0:维度1
dim1:维度2
3、torch.t(input)
功能:二维张量的转置,对于矩阵而言等同于torch.transpose(input, 0, 1)
4、torch.squeeze(input, dim=None, out=None)
功能:压缩长度为1的维度
参数:dim:如果为None,移除所有长度为1的维度;如果指定维度,当且仅当该轴长度为1时,可以被移除
5、torch.unsqueeze(input, dim, out=None)
功能:依据dim扩展维度为1的维度

五、张量的数学运算

总共可以分为三大类:加减乘除、对数指数幂函数、三角函数

下面展示的是各种数学运算的方法

python张量网络的缩并_python张量网络的缩并


介绍一下经常用到而且比较特殊的几个:

1、torch.add(input, alpha=1, other, out=None)

功能:逐元素计算,python张量网络的缩并_数据_02

参数:input:第一个张量

alpha:乘项因子

other:第二个张量

2、torch.addcdiv(input, value=1, tensor1, tensor2, out=None)

功能:逐元素计算,python张量网络的缩并_python张量网络的缩并_03

3、torch.addcmul(input, value=1, tensor1, tensor2, out=None)

功能:逐元素计算,python张量网络的缩并_pytorch_04