[AI] Pytorch with Scala, Vector, Matrix

JAsmine_log·2026년 2월 5일

torch

PyTorch의 텐서(tensor) 연산을 위한 핵심 모듈

차원별 구조



(자료 : https://wikidocs.net/233963)

스칼라 (0차원 텐서)

  • 단일 숫자 값
import torch

scalar = torch.tensor(3.14)
print(scalar.shape)  # torch.Size([])
print(scalar.dim())  # 0

Vector (1차원 텐서)

  • 숫자들의 1차원 배열
vector = torch.tensor([1, 2, 3, 4])
print(vector.shape)  # torch.Size([4])
print(vector.dim())  # 1

Matrix (2차원 텐서)

  • 숫자들의 2차원 배열

matrix = torch.tensor([[1, 2, 3],
                       [4, 5, 6]])
print(matrix.shape)  # torch.Size([2, 3])
print(matrix.dim())  # 2

Tensor (3차원 이상)

  • 더 높은 차원의 배열
  • 이미지, 비디오 데이터 등
tensor_3d = torch.randn(2, 3, 4)  # (배치, 높이, 너비)
print(tensor_3d.shape)  # torch.Size([2, 3, 4])

주요 연산

Vector 연산

v1 = torch.tensor([1.0, 2.0, 3.0])
v2 = torch.tensor([4.0, 5.0, 6.0])

# 내적 (dot product)
dot = torch.dot(v1, v2)  # 1*4 + 2*5 + 3*6 = 32

# 원소별 곱셈
elementwise = v1 * v2  # [4, 10, 18]

Matrix 연산


A = torch.tensor([[1.0, 2.0],
                  [3.0, 4.0]])
B = torch.tensor([[5.0, 6.0],
                  [7.0, 8.0]])

# 행렬 곱셈
C = torch.mm(A, B)
# 또는 C = A @ B

# 전치 (transpose)
A_T = A.T

Applications

이러한 구조를 통해 딥러닝에서 효율적인 수치 계산과 자동 미분이 가능함

  • Scala (0 dim) : 손실값(loss), 학습률(learning rate) 등
  • Vector (1 dim) : 단일 데이터 샘플의 특징(feature), 편향(bias)
  • matrix (2 dim) : 가중치(weights), 배치 데이터(batch)
  • Tensor (3+ dim) : 이미지(height×width×channel), 배치 이미지(batch×height×width×channel)
profile
Everyday Research & Development

0개의 댓글