Linear(torch)

오상윤·2023년 4월 13일
0

딥러닝

목록 보기
5/12

행렬 곱셈

Batch Matrix Multiplicaton(BMM)

  • 같은 갯수의 행렬 쌍들에 대해서 병렬로 행렬 곱 실행
  • e.g. (N,n,h) x (N,h,m) = (N,n,m)
import torch
x = torch.FloatTensor([[[1,2],
					   [3,4],
                       [5,6]],
                      [[7,8],
                       [9,10],
                       [11,12],
                      [[13,14],
                       [15,16],
                       [17,18]]])
y = torch.FloatTensor([[[1,2,2],
					   [1,2,2]],
                      [[1,3,3],
                       [1,3,3]],
                      [[1,4,4],
                       [1,4,4]]])
z = torch.bmm(x,y)
print(z.size())

torch.Size[[3, 3, 3]]

Linear Layer

  • 신경망의 가장 기본 구성 요소
  • Fully-connected (FC) Layer라고 불리기도 함
  • 내부 파라미터에 따른 선형 변환을 수행하는 함수
  • 함수의 파라미터를 잘 조절하면, 주어진 입력에 대해 원하는 출력을 만들 수 있다

Linear Layer 작동 방식

  • 각 입력 노드들에 weight(가중치)를 곱하고 모두 합친 뒤, bias(편향)을 더한다
  • 내부 가중치 파라미터 (weight parameter) W와 b에 의해 정의된다

Equations

  • 행렬 곱으로 구현 가능
  • n차원에서 m차원으로서의 선형 변환 함수
  • y = f(x) = x*W + b

Linear Layer 실습

Raw Linear Layer

import torch

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([[1, 1, 1],
					   [2, 2, 2],
                       [3, 3, 3],
                       [4, 4, 4]])

y= linear(x, W, b)
print(y.size)

torch.Size([4,2])

nn.Module

import torch.nn as nn
class MyLinear(nn.moduls):

    def __init__(self, input_dim=3, ouput_dim=2):
    	self.input_dim = input_dim
        self.output_dim = output_dim

        super().__init__()
        # 가중치(weight)
        self.W = torch.FloatTensor(input_dim, output_dim)
        # 편향(bias)
        self.b = torch.FloatTensor(output_dim)

    def forward(self, x):
    	# |x| = (batch_size, input_dim)
    	y = torch.matmu;(x, self.w) + self.b
        # |y| = (batch_size, input_dim) * (input_dim, output_dim)
        #	  = (batch_size, output_dim)
        return y

linear = MyLinear(3,2)
y = linear(X)
for p in linear.parameters():
	print(p)
아무것도 안나온다(학습이 안되기 때문에)    

correct : nn.Module

import torch.nn as nn
class MyLinear(nn.moduls):

    def __init__(self, input_dim=3, ouput_dim=2):
    	self.input_dim = input_dim
        self.output_dim = output_dim

        super().__init__()
        # 가중치(weight), nn.parameter로 감싸기
        self.W = nn.Parameter(torch.FloatTensor(input_dim, output_dim))
        # 편향(bias), nn.parameter로 감싸기
        self.b = nn.Parameter(torch.FloatTensor(output_dim))

    def forward(self, x):
    	# |x| = (batch_size, input_dim)
    	y = torch.matmu;(x, self.w) + self.b
        # |y| = (batch_size, input_dim) * (input_dim, output_dim)
        #	  = (batch_size, output_dim)
        return y

nn.Linear

linear = nn.Linear(3,2)

y = linear(x)

for p in linear.parameters():
	print(p)
profile
가보자가보자~

0개의 댓글

관련 채용 정보