熟悉C字符串的同学们应该都用过strcat()
函数,这个函数在C/C++程序中用于连接2个C字符串。在pytorch中,同样有这样的函数,那就是torch.cat()
函数.
先上源码定义:torch.cat(tensors,dim=0,out=None)
a=torch.tensor([[1,2,3,4],[1,2,3,4]])
b=torch.tensor([[1,2,3,4,5],[1,2,3,4,5]])
print(torch.cat((a,b),1))
#输出结果为:
tensor([[1, 2, 3, 4, 1, 2, 3, 4, 5],
[1, 2, 3, 4, 1, 2, 3, 4, 5]])
torch.cat()
函数是把各个tensor连接起来,这里的torch.chunk()
的作用是把一个tensor均匀分割成若干个小tensor
源码定义:torch.chunk(intput,chunks,dim=0)
c=torch.tensor([[1,4,7,9,11],[2,5,8,9,13]])
print(torch.chunk(c,3,1))
#输出结果为:
(tensor([[1, 4],
[2, 5]]), tensor([[7, 9],
[8, 9]]), tensor([[11],
[13]]))
这个函数可以说是torch.chunk()
函数的升级版本,它不仅可以按份数均匀分割,还可以按特定方案进行分割。
源码定义:torch.split(tensor,split_size_or_sections,dim=0)
torch.chunk()
一样了。section=[1,2,1,2,2]
d=torch.randn(8,4)
print(torch.split(d,section,dim=0))
#输出结果为:
(tensor([[ 0.5388, -0.8537, 0.5539, 0.7793]]), tensor([[ 0.1270, 2.6241, -0.7594, 0.4644],
[ 0.8160, 0.5553, 0.1234, -1.1157]]), tensor([[-0.4433, -0.3093, -2.0134, -0.4277]]), tensor([[-0.4297, 0.2532, 0.2789, -0.3068],
[ 1.4208, -0.1202, 0.9256, -1.2127]]), tensor([[ 0.3542, -0.4656, 1.2683, 0.8753],
[-0.2786, -0.2180, 0.3991, 0.5658]]))
参考文献:https://pytorch.org/docs/stable/torch.html