| 함수 | 설명 | ex |
|---|---|---|
| min | Tensor의 최솟값 | torch.min() |
| max | Tensor의 최댓값 | torch.max() |
| sum | Tensor의 합계 | torch.sum() |
| prod | Tensor의 곱 | torch.prod() |
| mean | Tensor의 평균 | torch.mean() |
| var | Tensor의 분산 | torch.var() |
| dim | 연산 차원 지정 | tensor.sum(dim=0) |
| size | Tensor의 크기 | tensor.size() |
| shape | Tensor의 형태 | tensor.shape |
| numel | Tensor의 요소 개수 | tensor.numel() |
예시
import torch
# 예시 tensor 생성
t = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 기본 연산 함수 사용 예시
print("최솟값:", torch.min(t))
print("최댓값:", torch.max(t))
print("합계:", torch.sum(t))
print("곱:", torch.prod(t))
print("평균:", torch.mean(t))
print("분산:", torch.var(t))
print("차원 0 기준 합계:", t.sum(dim=0))
print("크기:", t.size())
print("형태:", t.shape)
print("요소 개수:", t.numel())
# 실행 결과
# 최솟값: 1
# 최댓값: 6
# 합계: 21
# 곱: 720
# 평균: 3.5000
# 분산: 2.9167
# 차원 0 기준 합계: tensor([5, 7, 9])
# 크기: torch.Size([2, 3])
# 형태: torch.Size([2, 3])
# 요소 개수: 6
| 함수 | 설명 | 사용 예시 |
|---|---|---|
| zeros | 모든 요소가 0인 Tensor | torch.zeros() |
| ones | 모든 요소가 1인 Tensor | torch.ones() |
| zeros_like | 입력 Tensor와 같은 크기의 0 Tensor | torch.zeros_like() |
| ones_like | 입력 Tensor와 같은 크기의 1 Tensor | torch.ones_like() |
| 함수 | 설명 | 사용 예시 |
|---|---|---|
| rand | 0과 1 사이의 균등 분포에서 난수를 생성하는 Tensor | torch.rand() |
| randn | 평균이 0이고 표준 편차가 1인 표준 정규 분포에서 난수를 생성하는 Tensor | torch.randn() |
| rand_like | 입력 Tensor와 같은 크기와 자료형을 가지는 난수 Tensor (0과 1 사이의 균등 분포에서 난수 생성) | torch.rand_like() |
| randn_like | 입력 Tensor와 같은 크기와 자료형을 가지는 난수 Tensor (평균이 0이고 표준 편차가 1인 표준 정규 분포에서 난수 생성) | torch.randn_like() |
예시
t = torch.tensor([[1, 2], [3, 4]])
# 함수 사용 예시
print("zeros(2,2):\n", torch.zeros(2, 2))
print("ones(2,2):\n", torch.ones(2, 2))
print("zeros_like(t):\n", torch.zeros_like(t))
print("ones_like(t):\n", torch.ones_like(t))
print("rand(2,2):\n", torch.rand(2, 2))
print("rand_like(t):\n", torch.rand_like(t))
# 실행 결과
# zeros(2,2):
# tensor([[0., 0.],
# [0., 0.]])
# ones(2,2):
# tensor([[1., 1.],
# [1., 1.]])
# zeros_like(t):
# tensor([[0, 0],
# [0, 0]])
# ones_like(t):
# tensor([[1, 1],
# [1, 1]])
# rand(2,2):
# tensor([[0.1234, 0.5678],
# [0.9012, 0.3456]]) # 실제 값은 매번 다름
# rand_like(t):
# tensor([[0.7890, 0.2345],
# [0.6789, 0.1234]]) # 실제 값은 매번 다름
| 함수 | 설명 | 사용 예시 |
|---|---|---|
| arange | 지정된 간격의 1차원 Tensor | torch.arange() |
예시
torch.arange(5) # tensor([0, 1, 2, 3, 4])
torch.arange(start=1, end=3, step=0.5) # tensor([1., 1.5, 2., 2.5])
성능 향상메모리 사용 최적화| 함수 | 설명 | 사용 예시 |
|---|---|---|
| empty | 초기화되지 않은 Tensor | torch.empty() |
| fill_ | Tensor를 지정된 값으로 채움 | tensor.fill_() |
torch.empty()
- 지정된 크기의 텐서 생성 (But, 초기화 X)
- 메모리를 할당하지만, 그 메모리에 어떤 특정한 값을 쓰지 않음
- 결과적으로, 텐서의 요소들은 메모리에 이미 있던
쓰레기 값을 가지게 됨
랜덤으로 생성된 것 같지만 실제로 무작위로 생성된 것은 아님
✨ empty로 생성된 텐서는 사용하기 전에 반드시 값을 할당해야 함
예시
torch.empty(3,2)
# tensor([[4.5916e-41, 1.4013e-45],
# [0.0000e+00, 0.0000e+00],
# [0.0000e+00, 1.4013e-45]]) # 값은 매번 다를 수 있음
t = torch.empty(2,3)
t.fill_(5)
# tensor([[5., 5., 5.],
# [5., 5., 5.]])
| 함수 | 설명 | 사용 예시 |
|---|---|---|
| fill_ | 지정된 값으로 텐서를 채움 | tensor.fill_(5) |
| zero_ | 모든 원소를 0으로 채움 | tensor.zero_() |
| ones_ | 모든 원소를 1로 채움 | tensor.ones_() |
| uniform_ | 균일 분포의 난수로 채움 | tensor.uniform_(0, 1) |
| normal_ | 정규 분포의 난수로 채움 | tensor.normal_(mean=0, std=1) |
| random_ | 지정된 범위의 정수 난수로 채움 | tensor.random_(0, 10) |
| add_ | 텐서에 값을 더함 | tensor.add_(5) |
| sub_ | 텐서에서 값을 뺌 | tensor.sub_(3) |
| mul_ | 텐서에 값을 곱함 | tensor.mul_(2) |
| div_ | 텐서를 값으로 나눔 | tensor.div_(2) |
예시
t = torch.FloatTensor(2, 2)
t.fill_(5) # t를 5로 채움
# tensor([[5., 5.],
# [5., 5.]])
t.zero_() # t를 0으로 채움
# tensor([[0., 0.],
# [0., 0.]])
t.uniform_(0, 1) # t를 0~1 사이 균일 분포 난수로 채움
# tensor([[0.1234, 0.5678],
# [0.9012, 0.3456]])
t.normal_() # t를 정규 분포 난수로 채움
# tensor([[-0.1234, 0.5678],
# [ 0.9012, -0.3456]])
t.random_(0, 10) # t를 1~10사이 난수로 채움
# tensor([[3., 7.],
# [1., 9.]])
t.add_(1) # t에 1을 더함
# tensor([[4., 8.],
# [2., 10.]])
t.mul_(2) # t에 2를 곱함
# tensor([[ 8., 16.],
# [ 4., 20.]])
# List로 Tensor 생성
list_2d_tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
# Numpy 배열로 Tensor 생성
numpy_2d_array = np.array([[1, 2, 3], [4, 5, 6]])
numpy_2d_tensor = torch.from_numpy(numpy_2d_array)
| 함수 | 설명 | 사용 예시 |
|---|---|---|
| IntTensor | 32비트 정수형 Tensor | torch.IntTensor() |
| FloatTensor | 32비트 부동소수점 Tensor | torch.FloatTensor() |
| ByteTensor | 8비트 부호 없는 정수형 Tensor | torch.ByteTensor() |
| CharTensor | 8비트 부호 있는 정수형 Tensor | torch.CharTensor() |
| ShortTensor | 16비트 정수형 Tensor | torch.ShortTensor() |
| LongTensor | 64비트 정수형 Tensor | torch.LongTensor() |
| DoubleTensor | 64비트 부동소수점 Tensor | torch.DoubleTensor() |
예시
a, b, c = 1, 2, 3
torch.IntTensor([a, b, c]) # tensor([1, 2, 3], dtype=torch.int32)
torch.FloatTensor([a, b, c]) # tensor([1., 2., 3.], dtype=torch.float32)
AI 분야에서 GPU를 활용하는 이유
병렬 처리 능력 / 훈련, 추론 속도 향상 / 경제적 이점(시간 단축, 에너지 절약)
CUDA Tensor를 다루기 위한 기능들
| 기능 | Code |
|---|---|
| Tensor의 디바이스 확인 | tensor.device |
| CUDA 사용 가능 여부 확인 | torch.cuda.is_available() |
| CUDA device 이름 확인 | torch.cuda.get_device_name(device=0) |
| Tensor GPU에 할당 | torch.tensor([1, 2]).to(‘cuda’) torch.tensor([1, 2]).cuda() |
| Tensor GPU -> CPU | tensor.to(device = 'cpu') tensor.cpu() |
완전한 복사본이 필요할 때 사용차이점
- 메모리 사용
clone: 새로운 메모리 할당
detach: 원본 텐서와 메모리 공유- 계산 그래프
clone: 계산 그래프 유지
detach: 계산 그래프에서 분리- 변경 영향
clone: clone()으로 생성된 텐서를 변경해도 원본에 영향을 주지 않음
detach: detach()로 생성된 텐서를 변경하면 원본도 함께 변경
예시
t = torch.tensor([1, 2, 3]) # tensor([1, 2, 3])
t1 = t.clone() # tensor([1, 2, 3])
t2 = t.detach() # tensor([1, 2, 3])