텐서 기본 생성
torch.tensor() vs torch.Tensor() — 헷갈리지 말자
섹션 제목: “torch.tensor() vs torch.Tensor() — 헷갈리지 말자”PyTorch를 처음 접할 때 가장 많이 헷갈리는 부분입니다. 소문자 tensor와 대문자 Tensor는 완전히 다르게 동작합니다.
| 구분 | torch.tensor() | torch.Tensor() |
|---|---|---|
| 종류 | 함수 | 클래스 생성자 |
| 데이터 복사 | 항상 복사 | 복사하지 않을 수 있음 |
| dtype 추론 | 입력값에서 자동 추론 | 기본값 float32 고정 |
| 권장 여부 | ✅ 권장 | 특수 용도에만 사용 |
import torch
# torch.tensor() — 함수: 데이터로부터 생성t1 = torch.tensor([1, 2, 3])print(t1.dtype) # torch.int64 ← 정수 입력이므로 int64로 추론
t2 = torch.tensor([1.0, 2.0, 3.0])print(t2.dtype) # torch.float32 ← 실수 입력이므로 float32로 추론
# torch.Tensor() — 생성자: 항상 float32t3 = torch.Tensor([1, 2, 3])print(t3.dtype) # torch.float32 ← 정수를 넣어도 float32
# 빈 텐서 생성 (크기만 지정, 초기화 안 됨)t4 = torch.Tensor(3) # 길이 3인 1D 텐서 (쓰레기값)t5 = torch.Tensor(2, 3) # 2×3 텐서 (쓰레기값)print(t4.shape) # torch.Size([3])print(t5.shape) # torch.Size([2, 3])Python 리스트에서 텐서 생성
섹션 제목: “Python 리스트에서 텐서 생성”가장 흔한 사용 패턴입니다. 중첩 리스트로 다차원 텐서를 만들 수 있습니다.
# 1D 텐서t1d = torch.tensor([10, 20, 30, 40])print(t1d) # tensor([10, 20, 30, 40])print(t1d.shape) # torch.Size([4])
# 2D 텐서 (중첩 리스트)t2d = torch.tensor([ [1, 2, 3], [4, 5, 6]])print(t2d)# tensor([[1, 2, 3],# [4, 5, 6]])print(t2d.shape) # torch.Size([2, 3])
# 3D 텐서t3d = torch.tensor([ [[1, 2], [3, 4]], [[5, 6], [7, 8]]])print(t3d.shape) # torch.Size([2, 2, 2])
# 중첩 리스트의 크기가 불일치하면 오류# torch.tensor([[1, 2], [3]]) → ValueError: 크기 불일치Python 튜플에서 텐서 생성
섹션 제목: “Python 튜플에서 텐서 생성”리스트와 동일하게 동작합니다.
# 튜플에서 생성t_tuple = torch.tensor((1.0, 2.0, 3.0))print(t_tuple) # tensor([1., 2., 3.])
# 중첩 튜플t_nested = torch.tensor(((1, 2), (3, 4), (5, 6)))print(t_nested.shape) # torch.Size([3, 2])
# 리스트와 튜플 혼합도 가능t_mixed = torch.tensor([(1, 2), (3, 4)])print(t_mixed.shape) # torch.Size([2, 2])dtype 지정하기
섹션 제목: “dtype 지정하기”데이터 타입을 명시적으로 지정하면 의도치 않은 타입 변환을 방지할 수 있습니다.
# dtype 자동 추론t_auto = torch.tensor([1, 2, 3])print(t_auto.dtype) # torch.int64
# dtype 명시 지정t_f32 = torch.tensor([1, 2, 3], dtype=torch.float32)t_f64 = torch.tensor([1, 2, 3], dtype=torch.float64)t_i32 = torch.tensor([1, 2, 3], dtype=torch.int32)t_bool = torch.tensor([1, 0, 1], dtype=torch.bool)
print(t_f32.dtype) # torch.float32print(t_f64.dtype) # torch.float64print(t_i32.dtype) # torch.int32print(t_bool) # tensor([ True, False, True])주요 dtype 목록
섹션 제목: “주요 dtype 목록”| dtype | 줄임 표기 | 설명 | 메모리 |
|---|---|---|---|
torch.float32 | torch.float | 단정밀도 실수 (기본값) | 4 bytes |
torch.float64 | torch.double | 배정밀도 실수 | 8 bytes |
torch.float16 | torch.half | 반정밀도 (GPU 훈련용) | 2 bytes |
torch.int64 | torch.long | 64비트 정수 (인덱스용) | 8 bytes |
torch.int32 | torch.int | 32비트 정수 | 4 bytes |
torch.bool | — | 불리언 | 1 byte |
# 딥러닝에서 자주 쓰는 dtype 패턴weights = torch.tensor([0.1, 0.2, 0.3], dtype=torch.float32) # 모델 파라미터labels = torch.tensor([0, 1, 2], dtype=torch.long) # 클래스 인덱스mask = torch.tensor([True, False], dtype=torch.bool) # 마스킹device 지정하기
섹션 제목: “device 지정하기”텐서를 생성할 때 바로 GPU에 올릴 수 있습니다.
# CPU (기본값)t_cpu = torch.tensor([1.0, 2.0, 3.0])print(t_cpu.device) # cpu
# GPU — CUDAif torch.cuda.is_available(): t_gpu = torch.tensor([1.0, 2.0, 3.0], device='cuda') print(t_gpu.device) # cuda:0
# 특정 GPU 지정 t_gpu1 = torch.tensor([1.0], device='cuda:1')
# GPU — Apple Siliconif torch.backends.mps.is_available(): t_mps = torch.tensor([1.0, 2.0, 3.0], device='mps') print(t_mps.device) # mps
# 문자열 대신 torch.device 객체도 사용 가능device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')t = torch.tensor([1.0, 2.0], device=device)print(t.device)dtype과 device 동시 지정
섹션 제목: “dtype과 device 동시 지정”device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
t = torch.tensor( [[1, 2, 3], [4, 5, 6]], dtype=torch.float32, device=device)
print(t.dtype) # torch.float32print(t.device) # cuda:0 또는 cpuprint(t.shape) # torch.Size([2, 3])핵심 요약
섹션 제목: “핵심 요약”torch.tensor()(소문자) → 데이터로부터 생성, dtype 자동 추론, 항상 이것을 사용torch.Tensor()(대문자) → 클래스 생성자, 항상 float32, 빈 텐서에 사용- 중첩 리스트/튜플로 다차원 텐서 생성 가능
dtype=으로 데이터 타입 명시,device=으로 실행 장치 지정device변수를 미리 정의해두는 패턴을 습관화할 것