본문 바로가기
C.W.K.
Stream
Lesson 01 of 07 · published

torchvision 데이터셋과 v2 변환 API

~12 min · torchvision, v2, transforms

Level 0텐서 탐구자
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

내장 데이터셋과 현대적인 변환 파이프라인

torchvision은 MNIST, CIFAR-10/100, ImageNet, COCO처럼 바로 쓸 수 있는 데이터셋과 변환 파이프라인을 제공해. 현재 권장 API는 torchvision.transforms.v2야. 기존의 torchvision.transforms도 작동하지만 새 코드에는 v2를 사용해.

왜 v2가 중요할까?

  • tv_tensors(이미지, BoundingBoxes, 마스크, Video)를 기본 지원해. 탐지와 분할 작업에 특히 중요해.
  • 이미지, 경계 상자, 마스크 같은 여러 입력에 같은 변환을 정확히 적용해. 예를 들어 셋을 한 번에 같은 각도로 회전할 수 있어.
  • 흔한 연산을 새로 구현해 이전 버전보다 훨씬 빠른 경우가 많아.
  • PIL 이미지 변환과 텐서 변환의 역할을 깔끔하게 나눠.

표준 전처리 순서

ImageNet으로 사전 학습된 모델을 다룰 때 다음 구성을 계속 만나게 될 거야:

  1. ToImage(): 입력을 v2 기본 형식인 tv_tensor.Image로 감싸.
  2. ToDtype(torch.float32, scale=True): 값을 [0, 1] 범위의 float32로 바꿔.
  3. Resize(256): 짧은 변의 길이를 256으로 맞춰.
  4. CenterCrop(224): 중앙의 224x224 영역을 잘라.
  5. Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]): ImageNet 통계로 정규화해. 이 값은 기억해 두는 게 좋아.

Code

내장 데이터셋: CIFAR10 예·python
import torch
import torchvision
from torchvision import datasets
import torchvision.transforms.v2 as T

transform = T.Compose([
    T.ToImage(),
    T.ToDtype(torch.float32, scale=True),
    T.Resize(32),
    T.Normalize(mean=[0.4914, 0.4822, 0.4465],
                std=[0.2470, 0.2435, 0.2616]),  # CIFAR10-specific
])

train_ds = datasets.CIFAR10('./data', train=True, download=True, transform=transform)
test_ds  = datasets.CIFAR10('./data', train=False, download=True, transform=transform)
print(len(train_ds), len(test_ds))   # 50000 10000
print(train_ds[0][0].shape, train_ds[0][1])  # torch.Size([3, 32, 32]) 6
표준 ImageNet 전처리·python
import torch
import torchvision.transforms.v2 as T

# This is the chain that matches every torchvision pretrained model
preprocess = T.Compose([
    T.ToImage(),
    T.ToDtype(torch.float32, scale=True),
    T.Resize(256),
    T.CenterCrop(224),
    T.Normalize(mean=[0.485, 0.456, 0.406],
                std=[0.229, 0.224, 0.225]),
])

# But the modern recommended way is to ASK the model for its transforms:
from torchvision.models import resnet50, ResNet50_Weights
weights = ResNet50_Weights.IMAGENET1K_V2
preprocess = weights.transforms()
# weights.transforms() returns the EXACT preprocessing the model was trained with
v2의 핵심 장점: 여러 입력 변환·python
import torch
import torchvision.transforms.v2 as T
from torchvision import tv_tensors

# A scene with image + bounding boxes + segmentation mask
img = torch.randint(0, 255, (3, 224, 224), dtype=torch.uint8)
boxes = tv_tensors.BoundingBoxes(
    [[10, 20, 100, 150]], format='XYXY', canvas_size=(224, 224)
)
mask = tv_tensors.Mask(torch.zeros(224, 224, dtype=torch.uint8))

transform = T.Compose([
    T.RandomHorizontalFlip(p=1.0),
    T.RandomRotation(15),
])

# Apply to all three at once — boxes and mask transform consistently with image
img_t, boxes_t, mask_t = transform(img, boxes, mask)
print(img_t.shape, boxes_t, mask_t.shape)
# This was nearly impossible with the old transforms API.

External links

Exercise

v2 변환 파이프라인으로 CIFAR-10을 불러와. 변환한 이미지 하나의 자료형, 모양, 평균, 표준편차를 출력해. 그다음 정규화 없이 불러와 값의 범위가 [0, 1]인지 확인하고, 정규화를 추가했을 때 평균이 0, 표준편차가 1에 가까워지는지도 검증해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.