pytorch, tensorflow

[PyTorch] torch.cat(), torch.stack() 비교

2022. 10. 1. 10:54
목차
  1. 1. torch.cat()
  2. 2. torch.stack()

1. torch.cat()

torch.cat() 기능 정의는 다음과 같다.

Concatenates the given sequence of seq tensors in the given dimension. All tensors must either have the same shape (except in the concatenating dimension)

기준 차원에 대해 두 텐서의 요소를 연결하며(list의 extend), 기준 차원을 제외한 shape은 동일해야 한다.

import torch

t1 = torch.rand((6, 32))
t2 = torch.rand((4, 32))

torch.cat((t1, t2), dim=0).shape
>>>> torch.Size([10, 32])

torch.cat((t1, t2), dim=1).shape
>>>> torch.Size([4, 64])


t3 = torch.rand((4, 31))
torch.stack((t2, t3), dim=0).shape
>>>> RuntimeError: stack expects each tensor to be equal size, but got [4, 32] at entry 0 and [4, 31] at entry 1

 

 

2. torch.stack()

torch.stack() 기능 정의는 다음과 같다.

Concatenates a sequence of tensors along a new dimension. All tensors need to be of the same size.

새로운 차원을 기준으로 두 텐서를 연결하며, 대상이 되는 텐서의 모양이 모두 같아야 한다.

t1 = torch.tensor([[1,2,3],[4,5,6]])
t2 = torch.tensor([[-1,-2,-3],[-4,-5, -6]])

print(t1, "\n", t2)
>>>> tensor([[1, 2, 3],
             [4, 5, 6]]) 
     tensor([[-1, -2, -3],
             [-4, -5, -6]])
            
torch.stack([t1,t2], dim=0)  # shape: [2, 2, 3]
>>>> tensor([[[ 1,  2,  3],
              [ 4,  5,  6]],

             [[-1, -2, -3],
              [-4, -5, -6]]])
             
 torch.stack([t1,t2], dim=1)   # shape: [2, 2, 3]
 >>>> tensor([[[ 1,  2,  3],
               [-1, -2, -3]],

              [[ 4,  5,  6],
               [-4, -5, -6]]])

 

 

 

728x90
저작자표시 비영리 변경금지 (새창열림)

'pytorch, tensorflow' 카테고리의 다른 글

[PyTorch] Embedding 추가하기  (0) 2022.10.01
[pytorch] torch.reshape에 관하여  (0) 2022.07.11
[tensorflow 2.0] model.save, model.save_weights 차이  (0) 2021.04.01
[pytorch] torch에서 parameter 접근하기  (0) 2021.03.19
  1. 1. torch.cat()
  2. 2. torch.stack()
'pytorch, tensorflow' 카테고리의 다른 글
  • [PyTorch] Embedding 추가하기
  • [pytorch] torch.reshape에 관하여
  • [tensorflow 2.0] model.save, model.save_weights 차이
  • [pytorch] torch에서 parameter 접근하기
Fine애플
Fine애플
이것저것
Fine애플
끄적끄적
Fine애플
전체
오늘
어제
  • 분류 전체보기 (167)
    • 논문 및 개념 정리 (27)
    • Pattern Recognition (8)
    • 개발 (57)
    • python 메모 (45)
    • pytorch, tensorflow (5)
    • 알고리즘 (9)
    • Toy Projects (4)
    • 통계이론 (2)
    • Reinforcement Learning (10)

블로그 메뉴

  • 홈

공지사항

인기 글

태그

  • BigBird
  • tensorflow
  • 알고리즘
  • 딥러닝
  • nlp
  • Docker
  • container
  • 언어모델
  • 자연어
  • reinforcement learning
  • transformer
  • PyTorch
  • pandas
  • python
  • ubuntu
  • 개발환경
  • Probability
  • GPU
  • Bert
  • miniconda

최근 댓글

최근 글

hELLO · Designed By 정상우.
Fine애플
[PyTorch] torch.cat(), torch.stack() 비교
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.