본문 바로가기
딥러닝/파이토치 딥러닝

4장. 선형계층

by sonysame 2024. 4. 10.

선형계층은 행렬의 곱과 벡터의 덧셈으로 이루어짐!

 

1. 행렬곱(matmul)

x=torch.FloatTensor([[1,2],[3,4],[5,6]])
y=torch.FloatTensor([[1,2],[1,2]])
z=torch.matmul(x,y)
print(z)
print(z.size()) // 3x2

 

2. 배치행렬곱(bmm)

bmm은 마지막 2개의 차원을 행렬 취급하여 병렬로 행렬 곱 연산 수행

x=torch.FloatTensor(3,3,2)
y=torch.FloatTensor(3,2,3)
z=torch.bmm(x,y)

print(z.size()) #3x3x3

 

3. 선형계층

W=torch.FloatTensor([[1,2],[3,4],[5,6]])
b=torch.FloatTensor([2,2])

def linear(x,W,b):
    y=torch.matmul(x,W)+b
    return y

x=torch.FloatTensor(4,3)
y=linear(x,W,b)
print(y)

 

4. torch.nn.Module 클래스 상속

  • torch.nn.Module을 상속받고, __init__과 forward 함수를 오버라이드
  • forward함수를 따로 호출하지 않음. nn.Module의 상속받은 객체는 __call__함수와 forward함수가 매핑되어있음. 
import torch.nn as nn

class MyLinear(nn.Module):
    def __init__(self, input_dim=3, output_dim=2):
        self.input_dim=input_dim
        self.output_dim=output_dim

        super().__init__()
        self.W=torch.FloatTensor(input_dim, output_dim)
        self.b=torch.FloatTensor(output_dim)


    def forward(self, x):
        #|x|=(batch_size, input_dim)
        #|y|=(batch_size, output_dim)

        y=torch.matmul(x,self.W)+self.b
        return y
    
x=torch.FloatTensor(4,3)
linear=MyLinear(3,2)
y=linear(x)
print(y)

 

5. torch.nn.Parameter

import torch.nn as nn

class MyLinear(nn.Module):
    def __init__(self, input_dim=3, output_dim=2):
        self.input_dim=input_dim
        self.output_dim=output_dim

        super().__init__()
        self.W=nn.Parameter(torch.FloatTensor(input_dim, output_dim))
        self.b=nn.Parameter(torch.FloatTensor(output_dim))


    def forward(self, x):
        #|x|=(batch_size, input_dim)
        #|y|=(batch_size, output_dim)

        y=torch.matmul(x,self.W)+self.b
        return y
    
x=torch.FloatTensor(4,3)
linear=MyLinear(3,2)
y=linear(x)
for p in linear.parameters():
    print(p)

 

6. torch.nn.Linear

linear=nn.Linear(3,2)
y=linear(x)
print(y)

 

7. torch.nn.Module + torch.nn.Linear

class MyLinear(nn.Module):
    def __init__(self, input_dim=3, output_dim=2):
        self.input_dim=input_dim
        self.output_dim=output_dim

        super().__init__()
        self.linear=nn.Linear(input_dim, output_dim)

    def forward(self, x):
        y=self.linear(x)
        return y
linear=MyLinear()
y=linear(x)
print(y)

 

8. GPU이용..

텐서끼리의 연산은 같은 장치(디바이스)에서만 가능..

'딥러닝 > 파이토치 딥러닝' 카테고리의 다른 글

8장. 로지스틱 회귀  (1) 2024.05.01
7장 선형회귀(linear regression)  (0) 2024.04.22
6장 경사하강법  (0) 2024.04.22
5장. 손실함수  (0) 2024.04.10
3장 파이토치 튜토리얼  (0) 2024.04.04