콘텐츠로 이동

텐서 기본 생성

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() — 생성자: 항상 float32
t3 = 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])

가장 흔한 사용 패턴입니다. 중첩 리스트로 다차원 텐서를 만들 수 있습니다.

# 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: 크기 불일치

리스트와 동일하게 동작합니다.

# 튜플에서 생성
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 자동 추론
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.float32
print(t_f64.dtype) # torch.float64
print(t_i32.dtype) # torch.int32
print(t_bool) # tensor([ True, False, True])
dtype줄임 표기설명메모리
torch.float32torch.float단정밀도 실수 (기본값)4 bytes
torch.float64torch.double배정밀도 실수8 bytes
torch.float16torch.half반정밀도 (GPU 훈련용)2 bytes
torch.int64torch.long64비트 정수 (인덱스용)8 bytes
torch.int32torch.int32비트 정수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) # 마스킹

텐서를 생성할 때 바로 GPU에 올릴 수 있습니다.

# CPU (기본값)
t_cpu = torch.tensor([1.0, 2.0, 3.0])
print(t_cpu.device) # cpu
# GPU — CUDA
if 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 Silicon
if 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)

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.float32
print(t.device) # cuda:0 또는 cpu
print(t.shape) # torch.Size([2, 3])

  • torch.tensor() (소문자) → 데이터로부터 생성, dtype 자동 추론, 항상 이것을 사용
  • torch.Tensor() (대문자) → 클래스 생성자, 항상 float32, 빈 텐서에 사용
  • 중첩 리스트/튜플로 다차원 텐서 생성 가능
  • dtype= 으로 데이터 타입 명시, device= 으로 실행 장치 지정
  • device 변수를 미리 정의해두는 패턴을 습관화할 것