Pytorch basic operation1: cat, stack

sample code

1. concat

  • dim=1: 열 방향으로 concat(옆으로 붙임)
  • dim=0: 행 방향으로 concat(아래로 붙음)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
test = torch.randint(low=1, high=10, size=(3,10))
print(test, test.shape)
>>
tensor([[4, 1, 6, 6, 2, 6, 7, 4, 7, 4],
[4, 2, 1, 1, 4, 9, 5, 1, 7, 3],
[3, 2, 9, 6, 9, 1, 6, 7, 1, 6]]) torch.Size([3, 10])

# cat dim=1; 열 방향으로 concat
test_cat1 = torch.cat([test, test], dim=1)
print(test_cat1, test_cat1.shape)
>>
tensor([[4, 1, 6, 6, 2, 6, 7, 4, 7, 4, 4, 1, 6, 6, 2, 6, 7, 4, 7, 4],
[4, 2, 1, 1, 4, 9, 5, 1, 7, 3, 4, 2, 1, 1, 4, 9, 5, 1, 7, 3],
[3, 2, 9, 6, 9, 1, 6, 7, 1, 6, 3, 2, 9, 6, 9, 1, 6, 7, 1, 6]]) torch.Size([3, 20])

# cat dim=0; 행 방향으로 concat
test_cat2 = torch.cat([test, test], dim=0)
print(test_cat2, test_cat2.shape)
>>
tensor([[4, 1, 6, 6, 2, 6, 7, 4, 7, 4],
[4, 2, 1, 1, 4, 9, 5, 1, 7, 3],
[3, 2, 9, 6, 9, 1, 6, 7, 1, 6],
[4, 1, 6, 6, 2, 6, 7, 4, 7, 4],
[4, 2, 1, 1, 4, 9, 5, 1, 7, 3],
[3, 2, 9, 6, 9, 1, 6, 7, 1, 6]]) torch.Size([6, 10])

2. stack

  • 차원을 새로 만듦
  • 아래 샘플에서 결과물 차원에서 2 주의
    • eg. (3, 4) -> dim=1: (3, 2, 4); dim=0: (2, 3, 4);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
test = torch.randint(low=1, high=5, size=(3,4))
test
>>
tensor([[4, 2, 3, 2],
[1, 3, 3, 1],
[2, 1, 2, 4]])

# dim=1
test_stack1 = torch.stack([test, test], dim=1)
test_stack1, test_stack1.shape
>>
tensor([[[4, 2, 3, 2],
[4, 2, 3, 2]],

[[1, 3, 3, 1],
[1, 3, 3, 1]],

[[2, 1, 2, 4],
[2, 1, 2, 4]]])
torch.Size([3, 2, 4])

# dim=0
test_stack0 = torch.stack([test, test], dim=0)
test_stack0, test_stack0.shape
>>
tensor([[[4, 2, 3, 2],
[1, 3, 3, 1],
[2, 1, 2, 4]],

[[4, 2, 3, 2],
[1, 3, 3, 1],
[2, 1, 2, 4]]])
torch.Size([2, 3, 4])
< !-- add by yurixu 替换Google的jquery并且添加判断逻辑 -->