# torch.cat()과 torch.stack()은 어떻게 다른가요?

**URL:** <https://discuss.pytorch.kr/t/torch-cat-torch-stack/26>\
**Category:** 자주 묻는 질문&답변\
**Created:** [5월 19, 2021, 10:10오전 UTC](https://discuss.pytorch.kr/t/torch-cat-torch-stack/26 "2021-05-19T10:10:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![9bow](https://discuss.pytorch.kr/user_avatar/discuss.pytorch.kr/9bow/32/16301_2.png) [@9bow](https://discuss.pytorch.kr/u/9bow)\
**Post date:** [5월 19, 2021, 10:10오전 UTC](https://discuss.pytorch.kr/t/torch-cat-torch-stack/26/1 "2021-05-19T10:10:04Z")

</div>

공식 홈페이지와 [StackOverflow](https://stackoverflow.com/questions/tagged/pytorch) 등에서 자주 보이는 질문과 답변을 번역하고 있습니다.

다음 링크에서 원문을 함께 찾아보실 수 있습니다.

- 원문: [https://stackoverflow.com/questions/54307225/whats-the-difference-between-torch-stack-and-torch-cat-functions/54307331](https://stackoverflow.com/questions/54307225/whats-the-difference-between-torch-stack-and-torch-cat-functions/54307331)

* * *

## 질문

- `torch.cat()`과 `torch.stack()`은 어떤 차이점이 있나요?

---

<div class="post-metadata">

**Author:** ![9bow](https://discuss.pytorch.kr/user_avatar/discuss.pytorch.kr/9bow/32/16301_2.png) [@9bow](https://discuss.pytorch.kr/u/9bow)\
**Post date:** [4월 23, 2022, 6:26오전 UTC](https://discuss.pytorch.kr/t/torch-cat-torch-stack/26/2 "2022-04-23T06:26:41Z")

</div>

## 답변

- `torch.cat()`은 **주어진 차원** 을 기준으로 주어진 텐서들을 붙입(con **cat** enate)니다.  
`torch.stack()`은 **새로운 차원** 으로 주어진 텐서들을 붙입니다.
- 따라서, `(3, 4)`의 크기(shape)를 갖는 2개의 텐서 `A`와 `B`를 붙이는 경우,  
`torch.cat([A, B], dim=0)`의 결과는 `(6, 4)`의 크기(shape)를 갖고,  
`torch.stack([A, B], dim=0)`의 결과는 `(2, 3, 4)`의 크기를 갖습니다.

## 다른 답변

- 예를 들어 설명하기 위해, 아래 두 개의 텐서 `t1`, `t2`를 예시로 선언해보겠습니다.

```python
t1 = torch.tensor([[1, 2],
                   [3, 4]])
t2 = torch.tensor([[5, 6],
                   [7, 8]])

```

- 이 때, `torch.cat()`의 동작은 다음과 같습니다.

```python
>>> torch.cat((t1, t2), dim=0) # dim=0인 경우
tensor([[1, 2],
        [3, 4],
        [5, 6],
        [7, 8]])

```

```python
>>> torch.cat((t1, t2), dim=1) # dim=1인 경우
tensor([[1, 2, 5, 6],
        [3, 4, 7, 8]])

```

- `torch.stack()`은 다음과 같습니다.

```python
>>> torch.stack((t1, t2))
tensor([[[1, 2],
         [3, 4]],
 
        [[5, 6],
         [7, 8]]])

```

## 더 알아보기

- [torch.cat — PyTorch 2.10 documentation](https://pytorch.org/docs/stable/generated/torch.cat.html#torch.cat)
- [torch.stack — PyTorch 2.10 documentation](https://pytorch.org/docs/stable/generated/torch.stack.html#torch.stack)
