张量的操作
- 拼接
#将张量按维度dim进行拼接
#torch.cat(tensors, dim=0, out=None)
t = torch.ones((2,3))
t_0 = torch.cat([t,t],dim=0)
t_1 = torch.cat([t,t],dim=1)
print("t_0:{}shape:{}\nt_1:{}shape:{}\n".format(t_0,t_0.shape,t_1,t_1.shape))
#在新创建的维度dim上进行拼接,会扩张张量的维度
#torch.stack(tensors, dim=0, out=None)
t = torch.ones((2,3))
t_0 = torch.stack([t,t],dim=2)#已有前两个维度,在维度2上新增一个维度
t_1 = torch.stack([t,t],dim=0)#维度为0时,会将已有的tensor往后移
print("t_0:{}shape:{}\nt_1:{}shape:{}\n".format(t_0,t_0.shape,t_1,t_1.shape))
2.切分
#按照指定维度dim进行平均切分
# torch.chunk(input,chunks,dim=0)
# chunks:要切分的份数,不能整除时,最后一份张量小于其他张量
# 返回值:张量列表
t = torch.ones((2,5))
print(t,t.shape)
list_torch = torch.chunk(t,chunks=2,dim=1)
for idx,i in enumerate(list_torch):
print("第{}个张量:{}, shape is {}".format(idx,i,i.shape))
# 将张量按照维度dim进行切分
# torch.split(tensor=,split_size_or_sections=,dim=)
# split_size_or_sections:为int时,表示每一份的长度,为list时,按list元素切分
# 返回值:张量列表
t = torch.ones((2,5))
print(t,t.shape)
list_tensor = torch.split(t,2,dim=1)
for idx,i in enumerate(list_tensor):
print("第{}个张量:{}, shape is {}".format(idx,i,i.shape))
print("=====================================================================")
list_tensor = torch.split(t,[2,1,2],dim=1)
for idx,i in enumerate(list_tensor):
print("第{}个张量:{}, shape is {}".format(idx,i,i.shape))
3.索引
# 在维度dim上,按index索引数据
# torch.index_select()
# 返回值:依index索引数据拼接的张量
t = torch.randint(0,9,size=(3,3))
index = torch.tensor([0,2],dtype=torch.long)
t_select = torch.index_select(t,dim=0,index=index)
print("t:\n{}\nt_select:\n{}\n".format(t,t_select))
# 按mask中的True进行索引
# torch.masked_select(input,mask,out)
# mask:与input同形状的bool类型张量
t = torch.randint(0,9,size=(3,3))
mask = t.ge(5)
t_select = torch.masked_select(t,mask)
print("t:\n{}\nmask:\n{}\nt_select:\n{}\n".format(t,mask,t_select))
4.变换
# 变换张量形状
# note:当张量在内存中是连续时,新张量与input共享数据内存
# torch.reshape(input, shape)
t = torch.randperm(8)
t_reshape = torch.reshape(t,(2,4))
print("t:\n{}\nt_reshape:\n{}\n".format(t,t_reshape))
#当维度的其一为-1,表示该维度自适应
t_reshape = torch.reshape(t,(-1,4))
print("t:\n{}\nt_reshape:\n{}\n".format(t,t_reshape))
# 变换张量的两个维度
# torch.transpose(input, dim0,dim1)
# 二维张量转置
# torch.t()
# 对于矩阵,等价于torch.transpose(input,0,1)
# 压缩长度为1的维度
# torch.squeeze(input,dim=None,out=None)
#依据dim扩展维度
# torch.unsqueeze(input,dim,out=None)
张量的数学运算
1.加减乘除
#torch.add()
#torch.addcdiv()
#torch.addcmul()
2.对数,指数,幂函数
3.三角函数