콘텐츠로 이동

특수 텐서 생성

수열과 격자 — 구조화된 텐서 생성

섹션 제목: “수열과 격자 — 구조화된 텐서 생성”

난수 텐서가 무작위성을 담당한다면, 특수 텐서 함수들은 규칙적인 패턴을 가진 텐서를 만듭니다. 좌표 격자, 단위행렬, 등간격 수열 등이 이에 해당합니다.


Python의 range()와 유사하지만 텐서를 반환합니다.

arange(start, end, step)
start: 시작값 (포함)
end: 끝값 (미포함, exclusive)
step: 간격 (기본값 1)
import torch
# 기본: 0부터 시작
a1 = torch.arange(5)
print(a1) # tensor([0, 1, 2, 3, 4])
# start, end 지정
a2 = torch.arange(2, 8)
print(a2) # tensor([2, 3, 4, 5, 6, 7])
# step 지정
a3 = torch.arange(0, 10, 2)
print(a3) # tensor([0, 2, 4, 6, 8])
# 실수 step도 가능
a4 = torch.arange(0.0, 1.0, 0.2)
print(a4) # tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000])
# 역순 (음수 step)
a5 = torch.arange(10, 0, -2)
print(a5) # tensor([10, 8, 6, 4, 2])

시작값과 끝값 사이를 정확히 n개의 등간격 점으로 나눕니다. arange와 달리 끝값이 **포함(inclusive)**됩니다.

linspace(start, end, steps)
start: 시작값 (포함)
end: 끝값 (포함, inclusive)
steps: 원소 개수
# 0과 1 사이를 5개 점으로
l1 = torch.linspace(0, 1, steps=5)
print(l1) # tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
# -π 부터 π 까지 100개 점 (삼각함수 그래프용)
import math
x = torch.linspace(-math.pi, math.pi, steps=100)
y = torch.sin(x)
print(x.shape) # torch.Size([100])
print(y.shape) # torch.Size([100])
# 학습률 스케줄 시각화용 축 생성
epochs = torch.linspace(1, 100, steps=100)
print(epochs[:5]) # tensor([ 1., 2., 3., 4., 5.])
print(epochs[-1]) # tensor(100.) ← 끝값 포함

항목torch.arange()torch.linspace()
제어 기준간격(step) 지정개수(steps) 지정
끝값 포함❌ 미포함 (exclusive)✅ 포함 (inclusive)
주 용도인덱스, 정수 수열좌표축, 연속 구간
반환 dtypeint64 (정수 입력 시)float32
# 같은 구간을 다른 방식으로
a = torch.arange(0.0, 1.1, 0.25) # step=0.25, end는 미포함
l = torch.linspace(0.0, 1.0, 5) # 5개 점, end 포함
print(a) # tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
print(l) # tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
# 결과는 같지만 arange는 부동소수점 오차 위험 있음

torch.logspace() — 로그 스케일 수열

섹션 제목: “torch.logspace() — 로그 스케일 수열”

로그 스케일로 등간격인 수열을 생성합니다. 학습률처럼 여러 자릿수에 걸친 범위를 탐색할 때 유용합니다.

# 10^start 부터 10^end 까지 steps개
ls = torch.logspace(start=-3, end=0, steps=4)
print(ls) # tensor([1.0e-03, 1.0e-02, 1.0e-01, 1.0e+00])
# = [0.001, 0.01, 0.1, 1.0]
# 학습률 탐색 범위 생성
lr_candidates = torch.logspace(-5, -1, steps=5)
print(lr_candidates)
# tensor([1.0e-05, 1.0e-04, 1.0e-03, 1.0e-02, 1.0e-01])

대각선이 1이고 나머지가 0인 **단위행렬(항등행렬)**을 생성합니다.

eye(3):
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
# 정방 단위행렬
e3 = torch.eye(3)
print(e3)
# tensor([[1., 0., 0.],
# [0., 1., 0.],
# [0., 0., 1.]])
# 직사각형 단위행렬 (n행 m열)
e = torch.eye(3, 5)
print(e)
# tensor([[1., 0., 0., 0., 0.],
# [0., 1., 0., 0., 0.],
# [0., 0., 1., 0., 0.]])
# 실전: 원-핫 인코딩
num_classes = 5
labels = torch.tensor([0, 2, 4, 1])
one_hot = torch.eye(num_classes)[labels]
print(one_hot)
# tensor([[1., 0., 0., 0., 0.],
# [0., 0., 1., 0., 0.],
# [0., 0., 0., 0., 1.],
# [0., 1., 0., 0., 0.]])

두 1D 텐서로 2D 좌표 격자를 만듭니다. 함수 시각화나 위치 인코딩에 사용됩니다.

# 1D 축 정의
x = torch.arange(0, 3) # [0, 1, 2]
y = torch.arange(0, 4) # [0, 1, 2, 3]
# 2D 격자 생성 (indexing='ij': 행렬 인덱싱)
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
print(grid_x.shape) # torch.Size([3, 4])
print(grid_y.shape) # torch.Size([3, 4])
print(grid_x)
# tensor([[0, 0, 0, 0],
# [1, 1, 1, 1],
# [2, 2, 2, 2]])
print(grid_y)
# tensor([[0, 1, 2, 3],
# [0, 1, 2, 3],
# [0, 1, 2, 3]])
# 모든 (x, y) 좌표 쌍 얻기
coords = torch.stack([grid_x, grid_y], dim=-1)
print(coords.shape) # torch.Size([3, 4, 2])
print(coords[1, 2]) # tensor([1, 2]) ← x=1, y=2 지점
# z = sin(x) * cos(y) 함수의 격자 계산
x = torch.linspace(-math.pi, math.pi, 50)
y = torch.linspace(-math.pi, math.pi, 50)
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
z = torch.sin(grid_x) * torch.cos(grid_y)
print(z.shape) # torch.Size([50, 50])
print(z.min()) # ≈ -1.0
print(z.max()) # ≈ 1.0

  • torch.arange(start, end, step) → 간격 기준 수열, end 미포함
  • torch.linspace(start, end, steps) → 개수 기준 수열, end 포함, 좌표축에 적합
  • torch.logspace(start, end, steps) → 로그 스케일 수열, 학습률 탐색에 유용
  • torch.eye(n) → n×n 단위행렬, 원-핫 인코딩 생성에도 활용
  • torch.meshgrid(x, y, indexing='ij') → 2D 좌표 격자, indexing 명시 필수