[PYTORCH]텐서(Tensor)란?

신동혁·2022년 12월 11일
0

Pytorch

목록 보기
2/4

파이토치 공식문서 : https://tutorials.pytorch.kr/beginner/basics/tensorqs_tutorial.html

1.텐서(Tensor)란?

텐서(tensor)는 배열(array)이나 행렬(matrix)과 매우 유사한 특수한 자료구조입니다. PyTorch에서는 텐서를 사용하여 모델의 입력(input)과 출력(output), 그리고 모델의 매개변수들을 부호화(encode)합니다.

텐서는 GPU나 다른 하드웨어 가속기에서 실행할 수 있다는 점만 제외하면 NumPy 의 ndarray와 유사합니다. 실제로 텐서와 NumPy 배열(array)은 종종 동일한 내부(underly) 메모리를 공유할 수 있어 데이터를 복수할 필요가 없습니다. (NumPy 변환(Bridge) 참고) 텐서는 또한 (Autograd 장에서 살펴볼) 자동 미분(automatic differentiation)에 최적화되어 있습니다.

2.텐서 초기화하기

import torch
import numpy as np

# 1.데이터로부터 직접(directly) 생성하기
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

# 2.NumPy 배열로부터 생성하기
np_array = np.array(data)
x_np = torch.from_numpy(np_array)

# 3.다른 텐서로부터 생성하기
x_ones = torch.ones_like(x_data) # x_data의 속성을 유지합니다.
print(f"Ones Tensor: \n {x_ones} \n")
# 출력화면
# Ones Tensor:
# tensor([[1, 1],
#        [1, 1]])

x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data의 속성을 덮어씁니다.
print(f"Random Tensor: \n {x_rand} \n")
# 출력화면
# Random Tensor:
# tensor([[0.0965, 0.2738],
#        [0.9675, 0.2934]])

# 4.무작위(random) 또는 상수(constant) 값을 사용하기
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
# 출력화면
#Random Tensor:
#  tensor([[0.8398, 0.8787, 0.4099],
#         [0.6517, 0.2316, 0.1294]])

# Ones Tensor:
#  tensor([[1., 1., 1.],
#         [1., 1., 1.]])

# Zeros Tensor:
#  tensor([[0., 0., 0.],
#         [0., 0., 0.]])

3.텐서의 속성

  • shape
    텐서의 모양
  • dtype
    텐서의 자료형
  • device
    cpu, gpu같이 저장되는 장치

4.텐서 GPU 사용 및 연산

전치(transposing), 인덱싱(indexing), 슬라이싱(slicing), 수학 계산, 선형 대수, 임의 샘플링(random sampling) 등, 100가지 이상의 텐서 연산들을 여기 에서 확인할 수 있습니다.

각 연산들은 (일반적으로 CPU보다 빠른) GPU에서 실행할 수 있습니다. Colab을 사용한다면, Edit > Notebook Settings 에서 GPU를 할당할 수 있습니다.

# GPU가 존재하면 텐서를 이동합니다
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  print(f"Device tensor is stored on: {tensor.device}")

출력화면

Device tensor is stored on: cuda:0

해당 설정을 통해 GPU를 이용한 빠른 연산이 가능해진다. 다양한 연산에 대해서는 글 맨 위에 있는 링크를 참고해 알아본다.

profile
개발취준생

0개의 댓글