본문 바로가기
Python

[Python] PyTorch 텐서 차원 다루기

by teamnova 2025. 8. 26.
728x90

 

딥러닝에서는 차원(Dimension) 개념이 굉장히 중요합니다.
배치 크기(batch_size), 채널(channel), 높이(height), 너비(width) 같은 정보들이 모두 차원으로 표현되기 때문이죠.

이번 포스팅에서는 파이토치(PyTorch)에서 차원을 다루는 기본 스킬을 예제로 정리해보겠습니다.

 

전체 코드입니다.

 

import torch

# 1. 텐서(Tensor) 만들기
# -----------------------------
# 1차원 벡터 (길이 4)
a = torch.tensor([1, 2, 3, 4])
print("a:", a)
print("a.shape:", a.shape)  # torch.Size([4])

# 2차원 행렬 (2행 3열)
b = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("\nb:", b)
print("b.shape:", b.shape)  # torch.Size([2, 3])


# 2. 차원 늘리기 (unsqueeze)
# -----------------------------
# 특정 위치에 새로운 차원(축)을 추가
c = a.unsqueeze(0)  # 0번 차원에 추가 → (1, 4)
print("\nc:", c)
print("c.shape:", c.shape)

d = a.unsqueeze(1)  # 1번 차원에 추가 → (4, 1)
print("\nd:", d)
print("d.shape:", d.shape)


# 3. 차원 줄이기 (squeeze)
# -----------------------------
# 크기가 1인 차원을 제거
e = c.squeeze()  # (1, 4) → (4,)
print("\ne:", e)
print("e.shape:", e.shape)


# 4. 차원 바꾸기 (view, reshape)
# -----------------------------
# view: 메모리 연속적일 때만 사용 가능
# reshape: 메모리 불연속도 안전하게 변환
f = b.view(3, 2)   # (2, 3) → (3, 2)
print("\nf:", f)
print("f.shape:", f.shape)

g = b.reshape(-1)  # 1차원으로 펼치기
print("\ng:", g)
print("g.shape:", g.shape)


# 5. 차원 교환 (transpose, permute)
# -----------------------------
# transpose: 2차원 행렬 전치
h = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("\nh:", h)
print("h.shape:", h.shape)  # (2, 3)

h_t = h.transpose(0, 1)  # (2, 3) → (3, 2)
print("\nh_t:", h_t)
print("h_t.shape:", h_t.shape)

# permute: 다차원 텐서에서 원하는 순서대로 차원 재배치
i = torch.randn(2, 3, 4)  # (batch=2, height=3, width=4)
print("\ni.shape:", i.shape)

i_perm = i.permute(0, 2, 1)  # (2, 3, 4) → (2, 4, 3)
print("i_perm.shape:", i_perm.shape)

 

 

주요 함수:
- unsqueeze / squeeze : 차원 추가/제거
- view / reshape      : 모양 바꾸기
- transpose / permute : 차원 순서 바꾸기

 

 

결과입니다.