본문 바로가기

Libraries & Frameworks/PyTorch

[PyTorch 101] 파이토치의 기본 자료구조, 텐서(Tensor) - 기초

728x90

 

 

 

텐서(Tensor) 란?

  • 배열(array)이나 행렬(matrix)와 유사한 자료구조. (NumPy의 ndarray와 유사)
  • GPU나 다른 하드웨어 가속기에서 실행할 수 있음.
  • 텐서는 자동 미분(automatic differentiation)에 최적화.
  • 스칼라(scalar)를 0차원 텐서, 벡터(vector)를 1차원 텐서, 행렬(matrix)을 2차원 텐서라고 부르기도 함

 

 

 

텐서 초기화 방법의 예시

 - 자세한 내용은 공식 문서 참조

 

   1. 데이터로부터 직접 생성하기

      - 자료형은 자동으로 유추

import torch

data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

 

   2. NumPy 배열로부터 생성하기

      - 양방향 변환 가능

import torch
import numpy as np

data = [[1, 2], [3, 4]]

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

 

   3. 다른 텐서로부터 생성하기

      - override하지 않은 경우 인자로 주어진 shape와 datatype을 유지함

import torch

data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

x_ones = torch.ones_like(x_data)
x_rand = torch.rand_like(x_data, dtype=torch.float)

 

   4. 무작위 값이나 값을 사용하기

      - shape는 텐서의 차원(dimension)을 나타내는 튜플

import torch

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}")

 

   5. 초기화 되지 않은 텐서

      - C에서 초기화 하지 않은 변수처럼 다양한 값(NaN 포함)으로 구성됨 (환경에 따라 다른 듯)

import torch

x = torch.empty(4, 2)
print(x)

파이참 venv
colab

 

텐서의 속성 (Attributes)

tensor = torch.rand(3,4)

print(tensor.shape)
print(tensor.dtype)
print(tensor.device)

 

 

 

텐서의 연산 (Operation)

  • 보다 다양한 텐서 연산은 공식 문서 참조
  • 텐서는 기본적으로 CPU에 생성되지만, 아래와 같은 코드로 GPU 텐서를 명시할 수 있음
tensor = torch.rand(3,4)
print(tensor.device)

if torch.cuda.is_available():
    tensor = tensor.to("cuda")
    
print(tensor.device)

 

 

 

 

 

참조
 - 이수안 컴퓨터 연구소 유튜브
 - PyTorch 공식문서
 - 파이토치 한국 사용자 모임
반응형