본문 바로가기
Python Library/PyTorch

[PyTorch] 텐서 (Tensor)

by goatlab 2022. 1. 13.
728x90
반응형
SMALL

텐서 (Tensor)

 

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

 

import torch
import numpy as np

 

tensor는 GPU나 다른 하드웨어 가속기에서 실행할 수 있다는 점만 제외하면 numpy의 ndarray와 유사하다. 실제로 tensor와 numpy array는 종종 동일한 내부 (underly) 메모리를 공유할 수 있어 데이터를 복사할 필요가 없다. tensor는 자동 미분 (automatic differentiation)에 최적화되어 있다.

 

tensor 초기화

 

tensor는 여러가지 방법으로 초기화할 수 있다. 데이터로부터 직접 (directly) 생성하기 데이터로부터 직접 tensor를 생성할 수 있다. 데이터의 자료형 (data type)은 자동으로 유추한다.

 

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

 

numPy array로부터 생성하기

 

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

 

tensor는 numpy array로 생성할 수 있다.

 

다른 tensor로부터 생성

 

x_ones = torch.ones_like(x_data) # x_data의 속성을 유지
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data의 속성을 덮어씀
print(f"Random Tensor: \n {x_rand} \n")
Out:

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

Random Tensor:
 tensor([[0.4738, 0.5467],
        [0.5430, 0.1616]])

 

명시적으로 재정의 (override)하지 않는다면, 인자로 주어진 tensor의 속성 (모양 (shape), 자료형 (datatype))을 유지한다.

 

무작위 (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}")
Out:

Random Tensor:
 tensor([[0.7759, 0.1138, 0.4539],
        [0.6169, 0.2986, 0.2102]])

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

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

 

shape는 tensor의 차원 (dimension)을 나타내는 튜플 (tuple)로, 출력 tensor의 차원을 결정한다.

 

https://tutorials.pytorch.kr/beginner/basics/tensorqs_tutorial.html

 

텐서(Tensor) — PyTorch Tutorials 1.10.0+cu102 documentation

Note Click here to download the full example code 파이토치(PyTorch) 기본 익히기 || 빠른 시작 || 텐서(Tensor) || Dataset과 Dataloader || 변형(Transform) || 신경망 모델 구성하기 || Autograd || 최적화(Optimization) || 모델 저

tutorials.pytorch.kr

 

728x90
반응형
LIST

'Python Library > PyTorch' 카테고리의 다른 글

[PyTorch] 변형 (Transform)  (0) 2022.01.13
[PyTorch] DATASET / DATALOADER  (0) 2022.01.13
[PyTorch] NumPy 변환 (Bridge)  (0) 2022.01.13
[PyTorch] 텐서 속성 (Attribute) / 연산 (Operation)  (0) 2022.01.13
파이토치 (PyTorch)  (0) 2022.01.13