초기화 함수로 텐서 생성
초기화 함수가 필요한 이유
섹션 제목: “초기화 함수가 필요한 이유”딥러닝에서는 특정 값으로 미리 채워진 텐서가 자주 필요합니다. 예를 들어 마스크를 만들 때는 0과 1로, 편향(bias) 초기화에는 0으로, 누적 합산용 버퍼에는 0으로 시작합니다. torch.zeros(), torch.ones() 같은 초기화 함수들이 이 역할을 담당합니다.
기본 초기화 함수
섹션 제목: “기본 초기화 함수”torch.zeros() — 0으로 채우기
섹션 제목: “torch.zeros() — 0으로 채우기”import torch
# 1D: 길이 5인 텐서, 모두 0z1 = torch.zeros(5)print(z1) # tensor([0., 0., 0., 0., 0.])print(z1.dtype) # torch.float32 ← 기본값
# 2D: 3×4 텐서z2 = torch.zeros(3, 4)print(z2.shape) # torch.Size([3, 4])
# 크기를 튜플로도 지정 가능z3 = torch.zeros((2, 3, 4))print(z3.shape) # torch.Size([2, 3, 4])
# dtype 지정z_int = torch.zeros(3, dtype=torch.int32)print(z_int) # tensor([0, 0, 0])주요 사용처: 누적 합산 버퍼, 마스크 초기화, 편향 초기화
torch.ones() — 1로 채우기
섹션 제목: “torch.ones() — 1로 채우기”o1 = torch.ones(4)print(o1) # tensor([1., 1., 1., 1.])
o2 = torch.ones(2, 3)print(o2)# tensor([[1., 1., 1.],# [1., 1., 1.]])
# 실전: 패딩 마스크 (모두 유효함을 표시)attention_mask = torch.ones(8, 128, dtype=torch.long) # (배치, 시퀀스 길이)print(attention_mask.shape) # torch.Size([8, 128])주요 사용처: 어텐션 마스크 초기값, 모든 가중치를 1로 초기화
torch.full() — 임의의 값으로 채우기
섹션 제목: “torch.full() — 임의의 값으로 채우기”# 3×3 텐서를 7.0으로 채우기f1 = torch.full((3, 3), fill_value=7.0)print(f1)# tensor([[7., 7., 7.],# [7., 7., 7.],# [7., 7., 7.]])
# 정수로 채우기f2 = torch.full((2, 4), fill_value=-1, dtype=torch.int32)print(f2)# tensor([[-1, -1, -1, -1],# [-1, -1, -1, -1]], dtype=torch.int32)
# 실전: 패딩 토큰 인덱스로 채운 시퀀스 (PAD_ID = 0)PAD_ID = 0padded = torch.full((8, 50), fill_value=PAD_ID, dtype=torch.long)print(padded.shape) # torch.Size([8, 50])주요 사용처: 특정 상수값으로 초기화, 패딩 토큰 시퀀스
torch.empty() — 초기화 없이 생성
섹션 제목: “torch.empty() — 초기화 없이 생성”# 초기화하지 않음 — 메모리에 남아있던 값이 그대로 들어감e1 = torch.empty(3)print(e1) # tensor([1.4013e-45, 0.0000e+00, 1.4013e-45]) ← 예측 불가능!
e2 = torch.empty(2, 3)print(e2.shape) # torch.Size([2, 3])주요 사용처: 이후에 완전히 덮어쓸 버퍼, 성능 최적화가 필요한 경우
함수 선택 비교표
섹션 제목: “함수 선택 비교표”| 함수 | 채우는 값 | 속도 | 안전성 | 주요 용도 |
|---|---|---|---|---|
torch.zeros() | 0 | 보통 | ✅ 안전 | 버퍼 초기화 |
torch.ones() | 1 | 보통 | ✅ 안전 | 마스크, 초기화 |
torch.full() | 임의 상수 | 보통 | ✅ 안전 | 패딩, 상수 텐서 |
torch.empty() | 쓰레기값 | ⚡ 가장 빠름 | ⚠️ 주의 | 덮어쓸 버퍼 |
_like 패턴: 다른 텐서의 형태 복사
섹션 제목: “_like 패턴: 다른 텐서의 형태 복사”_like 접미사 함수들은 기존 텐서의 shape, dtype, device를 그대로 복사하여 새 텐서를 만듭니다. 설정값을 일일이 반복하지 않아도 되어 매우 편리합니다.
# 기준이 되는 텐서reference = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) # float32, cpu, shape (2,3)
# 같은 shape/dtype/device로 0 텐서 생성zeros = torch.zeros_like(reference)print(zeros)# tensor([[0., 0., 0.],# [0., 0., 0.]])print(zeros.dtype) # torch.float32 ← reference와 동일print(zeros.device) # cpu ← reference와 동일
# 같은 shape/dtype/device로 1 텐서 생성ones = torch.ones_like(reference)print(ones)# tensor([[1., 1., 1.],# [1., 1., 1.]])
# 같은 shape/dtype/device로 특정 값 텐서 생성filled = torch.full_like(reference, fill_value=3.14)print(filled)# tensor([[3.1400, 3.1400, 3.1400],# [3.1400, 3.1400, 3.1400]])
# 같은 shape/dtype/device로 미초기화 텐서 생성empty = torch.empty_like(reference)print(empty.shape) # torch.Size([2, 3])_like 패턴의 실전 활용
섹션 제목: “_like 패턴의 실전 활용”import torch.nn as nn
# 모델이 있을 때 출력과 같은 형태의 타겟 텐서 만들기model = nn.Linear(10, 5)output = model(torch.randn(32, 10)) # shape: (32, 5)
# 같은 shape으로 타겟 생성 (dtype 오버라이드 가능)target = torch.zeros_like(output)print(target.shape) # torch.Size([32, 5]) ← output과 동일
# GPU 텐서에서도 자동으로 같은 device 유지if torch.cuda.is_available(): gpu_tensor = torch.randn(4, 4, device='cuda') gpu_zeros = torch.zeros_like(gpu_tensor) print(gpu_zeros.device) # cuda:0 ← 자동으로 GPU에 생성전체 예시: 신경망 레이어 초기화 시뮬레이션
섹션 제목: “전체 예시: 신경망 레이어 초기화 시뮬레이션”# 간단한 Linear 레이어 파라미터를 수동으로 초기화하는 예시in_features = 128out_features = 64
# 가중치: 임의 초기화 예정이므로 empty 사용 후 채움weight = torch.empty(out_features, in_features)nn_init = torch.nn.initnn_init.kaiming_uniform_(weight) # 실제 초기화 적용
# 편향: 0으로 초기화bias = torch.zeros(out_features)
print(f"weight: {weight.shape}") # torch.Size([64, 128])print(f"bias : {bias.shape}") # torch.Size([64])print(f"bias 값 확인: {bias[:5]}") # tensor([0., 0., 0., 0., 0.])핵심 요약
섹션 제목: “핵심 요약”torch.zeros()→ 0으로 초기화, 가장 자주 사용torch.ones()→ 1로 초기화, 마스크에 유용torch.full(shape, value)→ 임의 상수로 초기화torch.empty()→ 초기화 없음, 값이 예측 불가, 성능용으로만_like접미사 → shape + dtype + device를 기존 텐서에서 자동 복사