einops 개념 및 사용법
einops는 배열 및 텐서를 직관적으로 변환할 수 있도록 설계된 Python 라이브러리입니다.
간결한 문자열 기반 표기법을 통해 reshape, transpose, reduce 등의 연산을 쉽게 수행할 수 있습니다.
지원 프레임워크: numpy, torch, tensorflow, jax
1. einops가 필요한 이유
기존의 numpy, torch, tensorflow 등의 텐서 조작(reshape, permute, transpose)은 복잡하고 가독성이 떨어질 수 있습니다.
import torch
x = torch.randn(16, 3, 64, 64) # (batch, channel, height, width)
x = x.permute(0, 2, 3, 1) # (batch, height, width, channel)
einops를 사용하면 다음처럼 간결하게 표현할 수 있습니다.
from einops import rearrange
x = rearrange(x, 'b c h w -> b h w c')
2. einops의 주요 기능
| 기능 | 설명 | 함수 |
|---|---|---|
| 재배열 (Rearrange) | 텐서의 차원 순서 변경 | rearrange |
| 축소 (Reduce) | 특정 차원을 줄이면서 연산 수행 | reduce |
| 재조합 (Repeat) | 특정 차원을 복제하여 확장 | repeat |
3. 주요 연산 예제
rearrange: 텐서 변형 (reshape, transpose)
from einops import rearrange
import numpy as np
x = np.random.random((2, 3, 4))
y = rearrange(x, 'b c h -> b h c')
print(y.shape) # (2, 4, 3)
reduce: 특정 차원 축소
from einops import reduce
x = np.random.random((2, 3, 4))
y = reduce(x, 'b c h -> b h', 'mean')
print(y.shape) # (2, 4)
repeat: 차원 확장 (broadcasting)
from einops import repeat
x = np.random.random((2, 3))
y = repeat(x, 'b f -> b f 4')
print(y.shape) # (2, 3, 4)
4. 다양한 예제
CNN: NCHW ↔ NHWC 변환
x = np.random.random((16, 3, 64, 64))
y = rearrange(x, 'b c h w -> b h w c')
print(y.shape) # (16, 64, 64, 3)
ViT (Vision Transformer) 패치 분할
img = np.random.random((1, 3, 256, 256))
patches = rearrange(img, 'b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1=16, p2=16)
print(patches.shape) # (1, 256, 768)
NLP: Transformer Multi-Head Attention에서 heads 추가
q = np.random.random((32, 128))
q_heads = rearrange(q, 'b (h d) -> b h d', h=8)
print(q_heads.shape) # (32, 8, 16)
5. einops vs 기존 방법 비교
| 연산 | 기존 방법 | einops |
|---|---|---|
| Reshape | x.view() | rearrange(x, 'b c h w -> b h w c') |
| Transpose | x.permute() | rearrange(x, 'b c h w -> b h w c') |
| Reduce (mean) | x.mean(dim=1) | reduce(x, 'b c h -> b h', 'mean') |
| Expand (repeat) | x.repeat() | repeat(x, 'b f -> b f 4') |
6. einops의 장점
- ✅ 가독성 증가: 직관적인 문자열 표현
- ✅ 프레임워크 독립적: numpy, torch, tensorflow, jax 등에서 사용 가능
- ✅ 코드 간결화: reshape, permute, transpose 등을 하나의 문법으로 처리
- ✅ 배치 연산 지원: 다차원 연산을 쉽게 수행
7. einops 요약
| 기능 | 함수 | 설명 |
|---|---|---|
| 재배열 (Rearrange) | rearrange(x, 'b c h w -> b h w c') | 차원 순서 변경 |
| 축소 (Reduce) | reduce(x, 'b c h -> b h', 'mean') | 특정 차원을 평균/합산으로 축소 |
| 확장 (Repeat) | repeat(x, 'b f -> b f 4') | 특정 차원을 반복하여 확장 |
'[Python] Code' 카테고리의 다른 글
| [Python] 자료구조 (0) | 2025.02.10 |
|---|---|
| [Python] Numpy 소개 (0) | 2025.02.09 |
| [Python] PyTorch 소개 (0) | 2025.02.09 |
| [Python] Einsum (0) | 2025.02.09 |