记录一种合并torch.Tensor的方法

a是形状为[2,3]的torch.tensor

b是形状为[2,3]的torch.tensor

期望输出:c.shape[2,2,3]

代码如下

a = a.unsqueeze(0)
b = b.unsqueeze(0)
c = torch.cat((a, b),0) 


 

import torch
 
a= torch.FloatTensor([[1,2,3],[1,2,3]])
b=torch.FloatTensor([[4,5,6]])
#按行拼接,结构列数不变,行变多
c=torch.cat([a,b],0)
print(c)
 
a= torch.FloatTensor([[1,2,3],[1,2,3]])
b=torch.FloatTensor([[4,5,6],[7,8,9]])
#按列拼接,结构行数不变,需要列相同
c=torch.cat([a,b],1)
print(c)

如果两个都是一维

import torch
 
a= torch.FloatTensor([1,0,1])
b=torch.FloatTensor([0,0,1])
 
c=torch.cat((a.unsqueeze(0),b.unsqueeze(0)),0)
print(c)