관리 메뉴

Bull

[pytorch] Tensor 정리 | study book 본문

AI programming/pytorch

[pytorch] Tensor 정리 | study book

Bull_ 2024. 8. 9. 22:11

Tensor

텐서는 "선형대수학에서 다중선형사상 또는 텐서는 선형 관계를 나타내는 다중선형대수학의 대상이다. 19세기에 카를 프리드리히 가우스가 곡면에 대한 미분 기하학을 만들면서 도입하였다. 기본적인 예는 내적과 선형 변환이 있으며 미분 기하학에서 자주 등장한다" 라는 어려운 말이 있지만 파이썬에서의 자료 구조로, 배열을 N차원으로 나타냈다고 정의하자.

Tensor 생성

import torch

# tensor 생성 함수 / 기본적으로 값을 복사해서 만든다.
print(torch.tensor([1,2,3]))
# tensor 생성 클래스 / Float 텐서로 생성되며 인스턴스를 만든다.
print(torch.Tensor([[1,2,3],[4,5,6]]))
# Long 형 텐서 생성
print(torch.LongTensor([1,2,3]))
# Float 형 텐서 생성
print(torch.FloatTensor([1,2,3]))
# 결과
tensor([1, 2, 3])
tensor([[1., 2., 3.],
        [4., 5., 6.]])
tensor([1, 2, 3])
tensor([1., 2., 3.])

torch.tensor는 함수여서 값 복사해서 반환해주는 역할 정도만 하고 torch.Tensor 말 그대로 인스턴스로 만들어줌.

Tensor 속성

import torch

# 0~1 사이의 무작귀 균등 분포 생성
tensor = torch.rand(1,2)
# tensor에 들어간 값
print(tensor)
# tensor size 모양
print(tensor.shape)
# tensor 데이터 타입
print(tensor.dtype)
# tensor 사용 시 사용된 장치 (가속기 여부)
print(tensor.device)
#결과
tensor([[0.3365, 0.9806]])
torch.Size([1, 2])
torch.float32
cpu

Tensor 차원 변환

import torch

tensor = torch.rand(1,2)
print(tensor)
print(tensor.shape)
# tensor 차원 변환, 데이터 유지됌.
tensor = tensor.reshape(2,1)
print(tensor)
print(tensor.shape)
# 결과
tensor([[0.4751, 0.5829]])
torch.Size([1, 2])
tensor([[0.4751],
        [0.5829]])
torch.Size([2, 1])

자료형 설정

import torch

# tensor 생성 시 자료형 설정 가능
tensor = torch.rand((3,3), dtype = torch.float)
print(tensor)
# 결과
tensor([[0.0213, 0.6192, 0.7093],
        [0.5057, 0.6741, 0.9389],
        [0.0713, 0.0636, 0.8057]])

장치 설정

import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
tensor = torch.rand((1,1),device=device)

# 연결된 device
print(device)
# tensor에 device를 알 수 있음
print(tensor)
# 결과
cuda
tensor([[0.1487]], device='cuda:0')

코랩에서 런타임 유형 변경하면 됌.

장치 변환

import torch

cpu = torch.FloatTensor([1,2,3])
gpu = cpu.cuda()
gpu2cpu = gpu.cpu()
cpu2gpu = cpu.to("cuda")
# cpu
print(cpu)
# gpu
print(gpu)
# cpu
print(gpu2cpu)
# gpu
print(cpu2gpu)
# 결과
tensor([1., 2., 3.])
tensor([1., 2., 3.], device='cuda:0')
tensor([1., 2., 3.])
tensor([1., 2., 3.], device='cuda:0')

numpy 를 tensor 로 변환

import torch
import numpy as np

ndarray = np.array([1,2,3],dtype=np.uint8)
# tensor 함수로 값 복사
print(torch.tensor(ndarray))
# Tensor 클래스로 인스턴스 생성
print(torch.Tensor(ndarray))
# numpy를 torch로 바꿔주는 함수
print(torch.from_numpy(ndarray))
# 결과
tensor([1, 2, 3], dtype=torch.uint8)
tensor([1., 2., 3.])
tensor([1, 2, 3], dtype=torch.uint8)

tensor 를 numpy 로 변환

import torch

tensor = torch.cuda.FloatTensor([1,2,3])
# torch로 정의된 tensor 를 numpy 로 변환
ndarray = tensor.detach().cpu().numpy()
# 결과 정상 출력
print(ndarray)
# numpy Type
print(type(ndarray))
# 결과
[1. 2. 3.]
<class 'numpy.ndarray'>

detach() 메소드는 현재 연산 그래프에서 분리된 새로운 텐서를 반환한다.
GPU에서 CPU로 바꾸고 numpy로 변환한다.

Tensor 유형

데이터 형식 의미  자료형 CPU Tensor GPU Tensor
Byte 8bit 정수, 부호 x torch.uint8 torch.ByteTensor torch.cuda.ByteTensor
Short 16bit 정수, 부호 o torch.short torch.ShortTensor torch.cuda.ShortTensor
int 32bit 정수, 부호 o torch.int torch.IntTensor torch.cuda.IntTensor
Long 64bit 정수, 부호 o torch.long torch.LongTensor torch.cuda.LongTensor
Binary16 16bit 부동 소수점 torch.half torch.HalfTensor torch.cuda.HalfTensor
Brain Floating Point 16it 부동 소수점 torch.bfloat16 torch.Bfloat16Tensor torch.cuda.Bfloat16Tensor
Float 32bit 부동 소수점 torch.float torch.FloatTensor torch.cuda.FloatTensor
Double 64bit 부동 소수점 torch.double torch.DoubleTensor torch.cuda.DoubleTensor
Boolean 논리 torch.bool torch.BoolTensor torch.cuda.BoolTensor
int8 8bit 정수, 부호 o torch.int8 torch.CharTensor torch.CharTensor
int16 16bit 정수, 부호 o torch. int16 torch.ShortTensor torch.cuda.ShortTensor
int32 32bit 정수, 부호 o torch. int32 torch.IntTensor torch.cuda.IntTensor
int64 64bit 정수, 부호 o torch. int64 torch.LongTensor torch.cuda.LongTensor
Float16 16bit 부동 소수점 torch.float16 torch.HalfTensor torch.cuda.HalfTensor
Float32 32bit 부동 소수점 torch. float32 torch.FloatTensor torch.cuda.FloatTensor
Float64 64bit 부동 소수점 torch. float64 torch.DoubleTensor torch.cuda.DoubleTensor
Complex32 32bit 복소수 torch.complex32    
Complex64 64bit 복소수 torch. complex64    
Complex128 128bit 복소수 torch. complex128    
Complex128 128bit 복소수 torch. cdouble    
Quantized int 양자화된 4bit, 부호 o torch.quint4x2 torch.ByteTensor  
Quantized int 양자화된 8bit, 부호 x torch. quint8 torch.ByteTensor  
Quantized int 양자화된 8bit, 부호 o torch. qint8 torch.CharTensor  
Quantized int 양자화된 32bit, 부호 o torch. qint32 torch.IntTensor  

참고 자료

https://product.kyobobook.co.kr/detail/S000209621433

 

파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습 | 윤대희 - 교보문고

파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습 | 트랜스포머는 딥러닝 분야에서 성능이 우수한 모델로 현대 인공지능 분야의 핵심 기술입니다. 트랜스포머와 비전 트랜스

product.kyobobook.co.kr

'AI programming > pytorch' 카테고리의 다른 글

[pytorch] einops.rearrange()  (0) 2024.04.13