본문 바로가기
C.W.K.
Stream
Lesson 02 of 11 · published

텐서 만들기

~15 min · factory, zeros, randn, arange

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

실제로 쓰게 될 팩토리 함수

텐서를 만드는 방법은 세 갈래야. Python 데이터로 만들기, 모양을 지정해 만들기, 다른 텐서를 본떠 만들기. 팩토리 함수는 많지만 실전 작업의 약 95%는 다음 여섯 함수로 해결할 수 있어.

함수만드는 값대표 용도
torch.tensorPython 목록이나 스칼라로 만든 텐서간단한 시험 데이터, 레이블
torch.zeros / ones0 또는 1로 채운 텐서편향 초기화, 마스크, 누산기
torch.randn표준 정규분포의 값가중치 초기화, 더미 입력
torch.rand[0, 1) 균등분포의 값확률, 드롭아웃과 비슷한 잡음
torch.arange정수 또는 실수 범위위치 인코딩, 인덱스
torch.full상수로 채운 텐서패딩 값, 마스크

torch.zeros_like(x), torch.randn_like(x), torch.empty_like(x) 같은 like 계열 함수는 x의 모양과 자료형, 장치를 그대로 이어받아. 기존 텐서와 같은 조건의 결과 텐서를 할당할 때 꼭 맞는 동작이고, 'expected cuda:0 got cpu' 오류의 90%를 예방해.

외워둘 스타일 규칙 두 가지

  • torch.tensor(np.random.randn(N))보다 torch.randn(N)을 써. NumPy를 거치는 과정은 불필요하고 자료형과 장치 계약을 조용히 깨뜨릴 수 있어.
  • 가능하면 텐서를 만들 때 device=...를 넘겨. CPU에 먼저 할당한 뒤 .to('cuda')로 옮기면 이유 없이 할당과 전송 비용이 늘어나.

Code

Python 데이터와 모양으로부터·python
import torch

# From Python lists / scalars
t1 = torch.tensor([1, 2, 3, 4])           # int64 by default for ints
t2 = torch.tensor([[1.0, 2.0], [3.0, 4.0]])  # float32 for floats
t3 = torch.tensor(3.14)                    # 0D scalar tensor

# Force a dtype
t4 = torch.tensor([1, 2, 3], dtype=torch.float32)
t5 = torch.tensor([0, 1, 1, 0], dtype=torch.bool)

# From shape — these all return a (3, 4) tensor
zeros = torch.zeros(3, 4)
ones = torch.ones(3, 4)
sevens = torch.full((3, 4), 7.0)
identity = torch.eye(4)
랜덤 텐서와 시퀀스·python
import torch

# Standard normal (mean 0, std 1) — the canonical weight init starting point
w = torch.randn(128, 64)

# Uniform [0, 1)
p = torch.rand(32)

# Random integers (low inclusive, high exclusive)
labels = torch.randint(0, 10, (32,))     # 32 labels in [0, 10)

# Sequences
torch.arange(0, 10, 2)         # tensor([0, 2, 4, 6, 8])
torch.linspace(0.0, 1.0, 5)    # tensor([0.0, 0.25, 0.5, 0.75, 1.0])
torch.logspace(0, 3, 4)        # tensor([1., 10., 100., 1000.])
*_like 가족: 친구의 메타데이터 복사·python
import torch

x = torch.randn(8, 3, 224, 224, device="cpu", dtype=torch.float32)

# Allocate a sibling tensor — same shape, dtype, AND device
buffer = torch.zeros_like(x)
noise = torch.randn_like(x)

# Without _like you'd have to repeat all three:
# buffer = torch.zeros(8, 3, 224, 224, dtype=x.dtype, device=x.device)
# That's the bug-magnet you avoid by using _like.

External links

Exercise

init_xavier(in_features, out_features) 함수를 작성해. 표준편차가 sqrt(2 / (in_features + out_features))인 정규분포에서 (out_features, in_features) 모양의 가중치 텐서를 뽑아 반환하면 돼. 출력의 표준편차를 nn.Linear(in, out).weight.std()와 비교해. 두 값은 비슷한 범위에 있어야 해.

Progress

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

댓글 0

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

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