빅데이타 & 머신러닝/Pytorch

파이토치 1. 기본 자료형 텐서

Terry Cho 2024. 8. 5. 16:32

파이토치는 기본 자료형으로 행렬을 표현하는 텐서라는 자료형을 사용한다.

아래 코드는 간단하게 배열로 부터 텐서를 생성하고, 이를 곱하는 코드이다. 곱셈은 matmul 함수를 이용하거나 @ 를 이용할 수 있다. 

# Multiply Tensors
import torch

a = torch.tensor([[1,2],[3,4]])
b = torch.tensor([[1],[1]])

c = torch.matmul(a, b)
print(c)
print(a@b)

 

GPU에 텐서 생성

파이토치에서는 텐서를 생성할때 텐서가 저장되는 메모리를 지정할 수 있다. 일반적인 메모리나 또는 GPU가 있을 경우 GPU 메모리를 지정할 수 있다.아래 코드는 GPU가 있을 경우 텐서 a,b를 GPU에 저장하고 서로 곱한 결과를 출력하는 코드이다. 

# prompt: in pytorch, 
# a = torch.tensor([[1,2],[3,4]])
# b = torch.tensor([[1],[1]])
# multiply a and b

import torch

if torch.cuda.is_available():
    print("CUDA is available")
    device = torch.device("cuda")
else:
    print("CUDA is not available")
    device = torch.device("cpu")

a = torch.tensor([[1, 2], [3, 4]],dtype=torch.float,device=device)
b = torch.tensor([[1], [1]],dtype=torch.float,device=device)

c = torch.matmul(a, b)

print(c)

 

만약에 CPU 메모리에 생성된 텐서가 있다면, {텐서}.to 명령어를 이용하여 GPU로 옮길 수 있다.

import torch

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

if torch.cuda.is_available():
    print("CUDA is available")
    a = a.to("cuda")

print(a.device)
print(a.shape)
print(a.dtype)

 

텐서의 기본 연산

텐서의 곱셈,덧셈,뺄셈, (요소곱) 및 전치 행렬 연산

import torch

a = torch.tensor([ [1,2],[3,4]])
b = torch.tensor([ [1,1],[2,2]])

print(a)
# 행렬 곱셈
print(a@b)
# 행렬 요소곱
print(a*b)
# 행렬 덧셈
print(a+b)
# 행렬 뺄셈
print(a-b)

c = torch.tensor([[1,2],[3,4]])
#전치 행렬
print(torch.t(c))
print(c.T)

텐서 인덱싱 

# 행렬 Indexing
import torch

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

print(a[0,1]) # 2
print(a[0,0:]) # row 0, column 0: 1,2
print(a[0:,0]) # row 0,1 & column 0 : 1,3
print(a[1,1]) # 4
print(a[...,-1]) #print last column 2,4
print(a[-1,...]) #print last row 3,4