TIL

내일배움캠프 본캠프 48일차

수현조 2025. 2. 6. 22:48

📌 PyTorch 

🔹 1. PyTorch 설치

!pip3 install torch torchvision torchaudio
  • PyTorch와 관련 패키지 설치

추가 패키지 설치:

!yes | pip install tqdm jupyter jupyterlab scikit-learn scikit-image tensorboard torchmetrics matplotlib pandas

🔹 2. 텐서(Tensor) 개념

📌 텐서의 차원(Dimension)

  1. 스칼라(Scalar) - 0차원
    scalar = torch.tensor(4)
    print(scalar.dim())  # 0
    print(scalar.item())  # Python 기본 숫자로 변환 가능
    
  2. 벡터(Vector) - 1차원 텐서
    vector = torch.tensor([3, 6, 9])
    print(vector.dim())   # 1
    print(vector.shape)   # torch.Size([3])
    
  3. 행렬(Matrix) - 2차원 텐서
    matrix = torch.tensor([[1, 2, 3], [4, 5, 6]])
    print(matrix.dim())   # 2
    print(matrix.shape)   # torch.Size([2, 3])
    
  4. 3차원 텐서
    tensor3D = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
    print(tensor3D.dim())  # 3
    print(tensor3D.shape)  # torch.Size([2, 2, 2])
    
  5. 4차원 이상 텐서
    • 딥러닝에서 CNN에서 사용하는 이미지 데이터는 4차원 텐서
    • [배치 크기, 채널 수, 높이, 너비] 형태

🔹 3. 텐서의 연산

텐서 기본 연산

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

# 덧셈
print(a + b)   # tensor([5, 7, 9])

# 곱셈
print(a * b)   # tensor([4, 10, 18])

# 행렬 곱셈 (dot product)
c = torch.tensor([[1, 2], [3, 4]])
d = torch.tensor([[5, 6], [7, 8]])
print(torch.matmul(c, d))  

3차원 행렬 곱셈

A = torch.rand(3, 5, 6)  # 3개의 (5x6) 행렬
B = torch.rand(3, 9, 5)  # 3개의 (9x5) 행렬

B_T = B.transpose(1, 2)  # (3, 5, 9)로 변환
result = torch.matmul(A, B_T)  # (3, 5, 9) 크기의 결과 행렬
print(result.shape)  # torch.Size([3, 5, 9])

B의 차원을 바꿔야 연산 가능! (transpose(1, 2))


🔹 4. 텐서의 데이터 변환

NumPy ↔ PyTorch 변환

import numpy as np

# NumPy → PyTorch
np_array = np.array([1, 2, 3])
torch_tensor = torch.tensor(np_array)

# PyTorch → NumPy
converted_np = torch_tensor.numpy()

🔹 5. 이미지 데이터와 텐서

이미지 데이터를 텐서로 변환

  • 이미지는 픽셀 값 (0~255)로 저장됨
  • PyTorch에서는 [높이, 너비, 채널] → [채널, 높이, 너비] 형태로 변환
from torchvision import transforms
from PIL import Image

image = Image.open("example.jpg")  # 이미지 로드
transform = transforms.ToTensor()  # PyTorch 텐서 변환
tensor_image = transform(image)
print(tensor_image.shape)  # [C, H, W]

🚀 정리

  • PyTorch의 기본 개념: 텐서(Tensor)란?
  • 차원(Dimension) 개념: 스칼라(0D) → 벡터(1D) → 행렬(2D) → 3D 텐서
  • 텐서 연산: 기본 연산, 행렬 곱셈 (matmul, einsum)
  • 데이터 변환: NumPy ↔ PyTorch, 이미지 → 텐서 변환