Pytorch教程[01]张量操作

一、张量拼接与切分

1.1 torch.cat()

功能:将张量按维度dim进行拼接
• tensors: 张量序列
• dim : 要拼接的维度

torch.cat(tensors, 
		  dim=0, 
		  out=None)

1.2 torch.stack()

功能:在新创建的维度dim上进行拼接
• tensors:张量序列
• dim :要拼接的维度

torch.stack(tensors, 
			dim=0, 
			out=None)

1.3 torch.chunk()

功能:将张量按维度dim进行平均切分
返回值:张量列表
注意事项:若不能整除,最后一份张量小于
其他张量
• input: 要切分的张量
• chunks : 要切分的份数
• dim : 要切分的维度

torch.chunk(input, 
			chunks, 
			dim=0)

1.4 torch.split()

功能:将张量按维度dim进行切分
返回值:张量列表
• tensor: 要切分的张量
• split_size_or_sections : 为int时,表示
每一份的长度;为list时,按list元素切分
• dim : 要切分的维度

torch.split(tensor, 
			split_size_or_sections, 
			dim=0)

二、张量索引

2.1 torch.index_select()

功能:在维度dim上,按index索引数据
返回值:依index索引数据拼接的张量
• input: 要索引的张量
• dim: 要索引的维度
• index : 要索引数据的序号

torch.index_select(input, 
				   dim, 
				   index, 
				   out=None)

2.2 torch.masked_select()

功能:按mask中的True进行索引
返回值:一维张量
• input: 要索引的张量
• mask: 与input同形状的布尔类型张量

torch.masked_select(input, 
					mask, 
					out=None)

三、张量变换

3.1 torch.reshape()

功能:变换张量形状
注意事项:当张量在内存中是连续时,新张
量与input共享数据内存
• input: 要变换的张量
• shape: 新张量的形状

torch.reshape(input, 
			  shape)

3.2 torch.transpose()

功能:交换张量的两个维度
• input: 要变换的张量
• dim0: 要交换的维度
• dim1: 要交换的维度

torch.transpose(input, 
				dim0, 
				dim1)

3.3torch.t()

功能:2维张量转置,对矩阵而言,等价于
torch.transpose(input, 0, 1)

torch.t(input)

3.4 torch.squeeze()

功能:压缩长度为1的维度(轴)
• dim: 若为None,移除所有长度为1的轴;
若指定维度,当且仅当该轴长度为1时,可
以被移除;

torch.squeeze(input, 
			  dim=None, 
			  out=None)

3.5 torch.unsqueeze()

功能:依据dim扩展维度
• dim: 扩展的维度

torch.usqueeze(input, 
			   dim, 
			   out=None)

四、张量数学运算

4.1加减乘除

torch.add()
torch.addcdiv()
torch.addcmul()
torch.sub()
torch.div()
torch.mul()

torch.add()
功能:逐元素计算 input+alpha×other
• input: 第一个张量
• alpha: 乘项因子
• other: 第二个张量

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

4.2对数,指数,幂函数

torch.log(input, out=None)
torch.log10(input, out=None)
torch.log2(input, out=None)
torch.exp(input, out=None)
torch.pow()

4.3三角函数

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)

猜你喜欢

转载自blog.csdn.net/weixin_43694096/article/details/123426146
今日推荐