PyTorch Basics_01

PytorchOperations

Pytorch doc : main

Pytorch Tensor

Tensor


다차원 Arrays 를 표현하는 PyTorch 클래스
사실상 numpy의 ndarray와 동일
(그러므로 TensorFlow의 Tensor와도 동일)
Tensor를 생성하는 함수도 거의 동일

>>> n_array=np.arange(10).reshape(2,5)
>>> print(n_array)
[[0 1 2 3 4]
 [5 6 7 8 9]]
>>> t_array=torch.FloatTensor(n_array)
>>> print(t_array)
tensor([[0., 1., 2., 3., 4.],
        [5., 6., 7., 8., 9.]])
>>> n_array.shape
(2, 5)
>>> t_array.shape
torch.Size([2, 5])
>>>


Tensor를 사용하는 이유는 GPU에서의 연산이 가능하기 때문

Tensor operations

nn.functional 모듈에서 딥러닝 연산을 위한 다양한 함수 지원

mm & matmul

>>> n2 = np.arange(10).reshape(5,2)
>>> t2 = torch.FloatTensor(n2)
>>> n1 = np.arange(10).reshape(2,5)
>>> t1 = torch.FloatTensor(n1)


>>> t1.mm(t2)
tensor([[ 60.,  70.],
        [160., 195.]])
>>>
# mm은 브로드케스팅 미지원, 브로드케스팅 시 matmul 연산
>>> a = torch.rand(5, 2, 3)
>>> b = torch.rand(3)
>>> a.mm(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: self must be a matrix
>>> a.matmul(b)
tensor([[0.6796, 0.9354],
        [0.7770, 0.7377],
        [0.3269, 0.2283],
        [0.9234, 0.3304],
        [0.9173, 0.7840]])
>>>

Softmax


텐서의 값을 확률로 변환해주는 소프트맥스 함수

>>> import torch.nn.functional as F
>>> tensor = torch.FloatTensor([0.5, 0.7, 0.1])
>>> h_tensor = F.softmax(tensor, dim=0)
>>> h_tensor
tensor([0.3458, 0.4224, 0.2318])
>>>

Argmax


텐서에서 가장 큰 원소의 인덱스 번호를 리턴해 주는 argmax 함수

>>> a = torch.randn(4, 4)
>>> a
tensor([[-0.0872,  1.4650, -1.5463, -1.1279],
        [-0.4658, -0.8992,  0.3674, -0.7540],
        [-1.1629,  0.4612,  1.3172, -0.0475],
        [ 0.0782,  1.6749, -0.0573,  1.3400]])
>>> torch.argmax(a)
tensor(13)
>>>

one_hot


tensor의 값이 1의 인덱스가 된다.

>>> a=torch.arange(0, 5) % 3
>>> a
tensor([0, 1, 2, 0, 1])
>>> F.one_hot(a)
tensor([[1, 0, 0],
        [0, 1, 0],
        [0, 0, 1],
        [1, 0, 0],
        [0, 1, 0]])

>>> F.one_hot(torch.arange(0, 5) % 3, num_classes=5)
tensor([[1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 1, 0, 0],
        [1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0]])


>>> F.one_hot(torch.arange(0, 6).view(3,2) % 3)
tensor([[[1, 0, 0],
         [0, 1, 0]],

        [[0, 0, 1],
         [1, 0, 0]],

        [[0, 1, 0],
         [0, 0, 1]]])
>>>

AutoGrad


pytorch의 핵심인 자동 미분 함수

>>> w = torch.tensor(2.0,
# w의 기울기를 저장
... requires_grad=True)

#관계식을 선언
>>> y = w**2
>>> z = 10*y + 2

#z'를 구함 -> z=10*w^2+25 이므로 z'=20*w 이고 tensor w는 2.0 이므로 
>>> z.backward()

#w가 2.0에서의 기울기 w.gard 는 40
>>> w.grad
tensor(40.)
>>>

from_numpy

zeros

zeros_like

max


피라미터를 input 하나만 줄 경우 input에서 가장 큰 원소(tensor)를 리턴

피라미터가 input,dim일 경우 input에서 입력한 dim에 따라(dim-> tensor shape(0,1,2,....))
가장 큰 원소(tensor)와 인덱스를 리턴

>>> temp=np.arange(30).reshape(2,3,5)
>>> temp
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14]],

       [[15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29]]])
>>> d=torch.from_numpy(temp)
>>> d
tensor([[[ 0,  1,  2,  3,  4],
         [ 5,  6,  7,  8,  9],
         [10, 11, 12, 13, 14]],

        [[15, 16, 17, 18, 19],
         [20, 21, 22, 23, 24],
         [25, 26, 27, 28, 29]]], dtype=torch.int32)
         
# dim이 0 일경우 -> 입력이 (2,3,5)모양이므로 2에서 가장 큰 텐서를 찾아서 리턴한다.
>>> torch.max(d,0)
torch.return_types.max(
values=tensor([[15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29]], dtype=torch.int32),
        #인덱스는 0번째 dim 의 모양인 (3,5) 형태인것을 확인할 수 있다.
indices=tensor([[1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1]])) 

# dim이 1 일경우 -> 입력이 (2,3,5) 모양이므로 3에서(행에서) 가장 큰 텐서를 찾는다.
>>> torch.max(d,1)
torch.return_types.max(
values=tensor([[10, 11, 12, 13, 14],
        [25, 26, 27, 28, 29]], dtype=torch.int32),
        # 1번째 dim 모양인 (5) 형태인것을 확인할 수 있다.
indices=tensor([[2, 2, 2, 2, 2],
        [2, 2, 2, 2, 2]]))

# dim이 2 인경우 -> 입력인 (2,3,5)모양의 5에서(열에서) 가장 큰 원소(텐서)를 찾는다.
>>> torch.max(d,2)
torch.return_types.max(
values=tensor([[ 4,  9, 14],
        [19, 24, 29]], dtype=torch.int32),
		#2번째 dim은 열의 원소들이므로 각 행당 하나씩 (2,3) 모양인것을 확일 할 수 있다.
indices=tensor([[4, 4, 4],
        [4, 4, 4]]))
>>>


에서 몇개나 맞았는지 확인하는 n_correct는 다음과 같이 돌아간다

>>> a=torch.tensor([0,1,2,3,4,5])
>>> b=torch.tensor([0,1,2,3,6,7])
>>> a==b
tensor([ True,  True,  True,  True, False, False])
>>> (a==b)
tensor([ True,  True,  True,  True, False, False])
>>> (a==b).sum()
tensor(4)
>>> (a==b).sum().item()
4
>>>

Tensor indexing


AutoGrad & Optimizer

torch.nn.Module


딥러닝을 구성하는 Layer의 base class

nn.Module을 상속하여 만들어지는 nn.Linear 의 구조

기본적인 선형 회귀 예시

forward & backward


모델이 어떤 식을 표현한다면, 해당 모델의 결과를 내는 방향이 순전파(forward)이고
해당 모델의 결과값에 대해 거꾸로 미분하는것이 역전파(backward)이다.
backward :
Layer에 있는 Parameter들의 미분을 수행
Forward의 결과값 (model의 output=예측치)과
실제값간의 차이(loss) 에 대해 미분을 수행
해당 값으로 Parameter 업데이트

1) 최적화할때 항상 grad를 초기화 시켜준다
2) loss 값을 구해주고
3) loss 값에 대해 피라미터들의 역전파를 계산하여
4) 가중치를 업데이트 시킨다.

해당 과정들은 실제 backward는 Module 단계에서 직접 지정가능하다.
Module에서 backward 와 optimizer 오버라이딩하여 사용할 수 있지만,
사용자가 직접 미분 수식을 써야하는 부담이 있기 때문에 자주 사용하지 않는다.
→ 쓸일은 없으나 순서는 이해할 필요는 있음

nn.Parameter


가중치가 저장되는 변수로써,Tensor 객체의 상속 객체
nn.Module 내에 attribute가 될 때는 required_grad=True 로 지정되어 학습 대상이 되는 Tensor
우리가 직접 지정할 일은 잘 없음 : 대부분의 layer에는 weights 값들이 지정되어 있음


datasets & dataloaders


추가적으로 과제에서 정리할것

datasets method __init__

datasets method __len__

datasets method __getitem__

torchvision

transforms methods

좋은 웹페이지 즐겨찾기