Programming/AI & ML

[OUTTA Alpha팀 Medical AI& 3D Vision 스터디] 기초 및 심화 머신러닝 2(Pytorch)

YeonJuJeon 2024. 12. 29. 19:34

1. Pytorch

1. Pytorch 개요

  • Tensorflow와 함께 딥러닝에서 가장 널리 사용되는 Python 기반 프레임워크.
  • New York University와 Facebook이 개발.
  • 장점:
    • 동적 그래프 지원: 실행 시마다 네트워크 구조 변경 가능.
    • Numpy와 유사한 문법: 배우기 쉽고 Pythonic.

2. Tensor (기본 자료 구조)

2.1 Tensor 생성

import torch
# 리스트/배열로 생성
t1 = torch.tensor([[1, 2], [3, 4]])
print(t1)

# 기본 텐서 생성 함수
t2 = torch.ones((2, 3))       # 1로 채우기
t3 = torch.zeros((2, 3))      # 0으로 채우기
t4 = torch.full((2, 3), 5)    # 특정 값으로 채우기
t5 = torch.arange(10)         # 연속된 값
t6 = torch.eye(3)             # 단위 행렬
t7 = torch.empty(2, 3)        # 초기화되지 않은 값
print(t2, t3, t4, t5, t6, t7)

 

2.2 Tensor 변환

 

Numpy ↔ Tensor:

import numpy as np
np_array = np.array([[1, 2], [3, 4]])

# Numpy → Tensor
t1 = torch.tensor(np_array)
t2 = torch.from_numpy(np_array)  # 뷰를 생성

# Tensor → Numpy
np_again = t1.numpy()
  • 차이점:
    • torch.tensor(): 복사본 생성 → 메모리 낭비 가능.
    • torch.from_numpy(): 뷰(View) 생성 → 메모리 공유.

3. Tensor 속성

3.1 속성 확인

t = torch.rand(3, 4)  # 랜덤 값 텐서
print(f"Shape: {t.shape}, DataType: {t.dtype}, Device: {t.device}")

 

3.2 속성 변경

# 차원 변경
t = t.reshape(4, 3)

# 데이터 타입 변경
t = t.int()

# GPU로 이동
if torch.cuda.is_available():
    t = t.to('cuda')

4. Indexing과 Slicing

t = torch.arange(1, 13).reshape(3, 4)

# Indexing
print(t[1])         # 특정 행
print(t[0, -1])     # 특정 값

# Slicing
print(t[1:-1])      # 행 슬라이싱
print(t[:2, 2:])    # 부분 슬라이싱

5. Tensor 연산

5.1 기본 연산

x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
y = torch.tensor([[5, 6], [7, 8]], dtype=torch.float32)

# 연산
print(x + y)  # 덧셈
print(x - y)  # 뺄셈
print(x * y)  # 요소별 곱
print(x @ y)  # 행렬 곱

 

5.2 축별 연산

z = torch.arange(1, 25).reshape(2, 4, 3)

# 축별 합
sum1 = torch.sum(z, axis=0)
sum2 = torch.sum(z, axis=1)
sum3 = torch.sum(z, axis=2)

print(sum1, sum2, sum3)

 

5.3 In-place 연산

x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
y = torch.tensor([[5, 6], [7, 8]], dtype=torch.float32)

# In-place 연산 (값이 x에 저장됨)
x.add_(y)
print(x)

6. Tensor 조작

6.1 텐서 합치기

a = torch.arange(12).reshape(3, 4)
b = torch.arange(12, 24).reshape(3, 4)

# Concatenation
concat_0 = torch.cat([a, b], axis=0)  # 행 기준
concat_1 = torch.cat([a, b], axis=1)  # 열 기준
print(concat_0, concat_1)

 

6.2 Transpose와 Permute

 

Transpose: 특정 두 차원의 위치를 변경.

a = torch.arange(16).reshape(2, 2, 4)
b = a.transpose(1, 2)
print(b)
 

Permute: 모든 차원의 위치를 자유롭게 변경.

c = a.permute((2, 0, 1))
print(c)

7. 주요 포인트

  1. Tensor 생성:
    • torch.tensor(), torch.ones(), torch.arange(), torch.eye().
  2. Tensor 변환:
    • Numpy ↔ Tensor: from_numpy(), .numpy().
    • 메모리 공유 여부 이해.
  3. 속성 변경:
    • 차원 변경: reshape().
    • 데이터 타입: int(), float().
    • GPU 이동: to('cuda').
  4. 기본 연산:
    • 요소별 연산: +, -, *, /.
    • 행렬 곱: @, torch.matmul().
  5. In-place 연산:
    • add_(), subtract_() 사용.
  6. 텐서 조작:
    • 축 기준 합치기: torch.cat().
    • 차원 변경: transpose(), permute().