본문 바로가기
경제학코딩 2023

[Keras Layer-(1)]

by 개발도사(진) 2023. 12. 16.

Keras Layer

Keras는 Python으로 작성된 오픈 소스 신경망 라이브러리이다. 딥러닝은 여러 계층의 Layer를 연결하여 모델을 구성하는데, Keras 역시 Layer를 기준으로 모델을 구성한다. 

Keras Layer에 대한 자세한 내용은 

Keras: Deep Learning for humans

 

Keras: Deep Learning for humans

A superpower for developers. The purpose of Keras is to give an unfair advantage to any developer looking to ship Machine Learning-powered apps. Keras focuses on debugging speed, code elegance & conciseness, maintainability, and deployability. When you cho

keras.io

위 사이트를 참고하여 확인할 수 있다. 이번 포스팅에서는 Keras의 Embedding Layer, Dense Layer에 대해 살펴본다.

 

들어가기에 앞서, 아래 코드를 실행하여 기본 설정을 해 준다.

!pip install -q keras-core #keras core 설치
import numpy as np
import os 

os.environ["KERAS_BACKEND"] = "torch" #환경변수 저장. Pytorch 사용할 것임을 선언

import keras_core as keras
import keras_core

 

Embedding Layer

Keras의 Embedding Layer는 자연어 처리에 자주 사용되는 특수 유형 레이어로, 양의 정수(index)를 고정된 크기의 dense vector로 바꿔 주는 역할을 하는 layer이다. 

keras.layers.Embedding(
    input_dim,
    output_dim,
    embeddings_initializer="uniform",
    embeddings_regularizer=None,
    embeddings_constraint=None,
    mask_zero=False,
    **kwargs
)

위 코드는 Keras.io의 공식 문서에 기술된 Embedding Layer이다. 우리는 이 포스팅에서 기본값이 설정된 영역은 건드리지 않고, input_dim, output_dim에 대해서만 다룰 것이다.

 

input_dim은 모델이 처리할 수 있는 최대 '단어'의 수, output_dim은 각 단어에 대한 embedding vector의 크기를 의미한다. 가령

emb = keras.layers.Embedding(100,2)

위와 같은 code는 우리가 사용할 단어(vacabulary, token)의 사이즈가 100이고, 이를 2차원의 dense vector로 바꿔 주겠다는 것을 의미한다.

 

Embedding Layer가 어떻게 작동하는지 확인하기 위해 다음과 같은 코드를 작성한다.

x = np.random.randint(0,100,(2,10))

machine learning은 기본적으로 batch 단위로 진행된다는 사실을 기억하자. 위 code는 0~99까지의 random number를 이용해서, 10개의 token으로 구성된 두 개의 example을 가진 batch를 만든다. 

여기에 Embedding Layer를 적용한 결과는 다음과 같다.

emb(x)

앞서 Embedding Layer의 정의를 설명할 때 언급했듯, 정수가 2차원의 dense vector로 변환되었음을 알 수 있다. 

 

Dense Layer

Dense Layer는 regression의 확장 개념이다. 아래 코드를 통해 앞서 다뤘던 regression을 Keras layer로 표현하게 해 준다.

keras.layers.Dense(n)

여기서 n은 matrix multiplication에 사용되는 coefficient들의 row 갯수이다. 즉 A@B+C의 형태에서, matrix A가 (nXm) matrix라면 keras.layers.Dense(n)을 사용하는 식이다.

 

가령 A@B+C 의 matrix multiplication 연산에서, A가 5*3 matrix, B,C가 1*3 matrix라고 하자. 그렇다면 Dense Layer가 regression을 하는 과정을 다음과 같은 그림으로 표현할 수 있다.

 

초록색이 B matrix의 각 원소,  노란색이 A matrix의 각 row에 (@B +C) 연산을 마친 결과값이라고 할 수 있다. 

'경제학코딩 2023' 카테고리의 다른 글

[Encoder Only Model with imdb]  (0) 2023.12.17
[Encoder Only Model with Random Data]  (1) 2023.12.17
[Keras Layer - (2)]  (0) 2023.12.16
[torch.nn-(2)]  (1) 2023.12.15
[torch.nn - (1)]  (0) 2023.12.14