pytorch-튜토리얼

허준·2022년 9월 19일

pytorch

import torch로 import해서 사용.

pytorch에서 쓰는 자료형은 tensor. 벡터라고 생각하면 얼추 맞다.

torch.zeros(3): 0.이 들어간 13 배열
torch.zeros((3,4)) 는 0.이 들어간 3
4 배열 차원은 마음껏 늘릴 순 있다.

tensor_a = torch.randn((2,3))
tensor_b = torch.randn((2,3)) 일때,

tensor_a+tensor_b는 대응되는 원소끼리 더해주고
tensor_a*tensor_b는 대응되는 원소끼리 곱해준다.

행렬곱을 하려면
tensor_a.T.matmul(tensor_b) 처럼 만들어 줘야 한다.

tensor.mean()
tensor.std()
tensor.max()
tensor.min()

으로 통계치 구할 수 있다.

MSE = torch.nn.MSELoss()
L1 = torch.nn.L1Loss()
scipy에서 처럼 이렇게 모델을 만들어 두고

a = torch.randn(5)
b = torch.zeros(5)
loss_MSE = MSE(a,b)
loss_l1 = L1(a,b)

텐서를 집어 넣어서 loss를 계산할 수도 있다. 결과물도 tensor로 나옴.

size를 수정하는 중요한 함수들

x=x.view(-1,3): 원래 x가 어떻게 생겼는지 모르겠으니 행의 길이는 torch에 맡기되, 열의 크기는 3이 되도록
x=x.unsqueeze(0) : 0번 인덱스에 차원이 1인 차원을 추가됨.
x=x.squeeze(): 차원이 1인것들을 압축. 3*1 짜리면 그냥 3짜리로

x = initpoint
for
in range(10):
x.requires_grad = True
loss = MSE(x, goal)
loss.backward()
x_grad = x.grad
with torch.no_grad():
x = x - x_grad
print("loss:{0:.4f}, x: {1}, x_grad: {2}".format(loss, x, x_grad))
기초 미분 방법. requires_grad를 True로 해서 미분
목표 loss는 0.
x.grad에 미분값이 들어 있다.

with torch.no_grad()는 autograd를 꺼버려서 메모리 사용량을 주리이고 연산속도를 높이는게 목표라고 함.

profile
퀀트 지망(Quant candidate)

0개의 댓글