2022年 11月 9日

Python-cat拼接操作

转载

举例

需要保证(除需要合并的维度外)其他维度均相等。参数dim指定需要合并的维度的索引号。

  • 默认dim=0就是合并(拼接)第一维,实现的时候是按行拼接,第一维度是加和,其他不变
  • dim=1合并(拼接第二维),实现的时候是按列拼接,第二维度是加和,其他不变
  1. import torch
  2. A = torch.ones(2,3)
  3. B = torch.ones(2,3)*2
  4. print('A:',A)
  5. print('A:',A.shape)
  6. print('----------------------')
  7. print('B:',B)
  8. print('B:',B.shape)
  9. print('-----------------------')
  10. C = torch.cat((A, B)) #默认dim=0
  11. print('C:',C)
  12. print('C:',C.shape)
  13. print('_______________________')
  14. D = torch.cat((A, B), dim=1)
  15. print('D:',D)
  16. print('D:',D.shape)

下面合并第三维举例

  1. import torch
  2. a = torch.rand(2, 10, 30)
  3. b = torch.rand(2, 10, 40)
  4. c = torch.cat([a, b], dim=2)
  5. print(c.shape)
  1. >>> c.shape
  2. torch.Size([2, 10, 70])