Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Keras 모델을 하나의 레이어처럼 다루고 Python으로 호출하는 방법

TensorFlow는 구글(Google)이 제공하는 머신러닝 프레임워크입니다. 오픈소스 기반으로 Python과 함께 사용되며, 알고리즘 구현, 딥러닝 애플리케이션 개발 등 다양한 용도로 활용됩니다. 연구 목적뿐 아니라 실제 프로덕션 환경에서도 널리 사용되고 있습니다.

Keras란 무엇인가?

Keras는 ONEIROS(Open ended Neuro-Electronic Intelligent Robot Operating System) 프로젝트의 연구 과정에서 개발된 딥러닝 API입니다. Python으로 작성된 고수준(high-level) API로, 머신러닝 문제를 해결하는 데 도움이 되는 생산적인 인터페이스를 제공하며 TensorFlow 프레임워크 위에서 동작합니다. 빠른 실험을 지원하도록 설계되었으며, 머신러닝 솔루션을 개발하고 캡슐화하는 데 필수적인 추상화 계층과 빌딩 블록을 제공합니다.

Keras는 뛰어난 확장성과 크로스 플랫폼 지원 능력을 갖추고 있습니다. TPU나 GPU 클러스터에서 실행할 수 있으며, 학습된 모델을 웹 브라우저나 모바일 환경에서도 구동할 수 있도록 내보내기가 가능합니다.

Keras는 이미 TensorFlow 패키지에 포함되어 있으며, 아래 코드 한 줄로 손쉽게 불러올 수 있습니다.

import tensorflow
from tensorflow import keras

Keras 모델을 레이어처럼 사용할 수 있을까?

네, 가능합니다. Keras 모델은 하나의 레이어처럼 취급하여 Python으로 직접 호출할 수 있습니다. Keras의 함수형 API(Functional API)를 활용하면 순차형(Sequential) API로 만든 모델보다 훨씬 유연한 구조의 모델을 만들 수 있습니다. 함수형 API는 비선형 토폴로지를 가진 모델을 다룰 수 있고, 레이어를 공유하거나 여러 입력과 출력을 처리할 수도 있습니다.

일반적으로 딥러닝 모델은 여러 레이어로 구성된 방향성 비순환 그래프(DAG, Directed Acyclic Graph)입니다. 함수형 API는 바로 이 레이어 그래프를 손쉽게 구축할 수 있게 해줍니다.

아래 코드는 Google Colaboratory에서 실행했습니다. Google Colab은 브라우저에서 별도 설정 없이 Python 코드를 실행할 수 있게 해주며, GPU를 무료로 사용할 수 있다는 장점이 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 만들어졌습니다.

예제 코드

다음은 인코더(encoder)와 디코더(decoder) 모델을 각각 정의한 뒤, 이들을 마치 레이어처럼 호출하여 오토인코더(autoencoder) 모델을 구성하는 코드입니다.

encoder_input = keras.Input(shape=(28, 28, 1), name="original_img")
print("Adding layers to the model")
x = layers.Conv2D(16, 3, activation="relu")(encoder_input)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.MaxPooling2D(3)(x)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.Conv2D(16, 3, activation="relu")(x)
print("Performing global max pooling")
encoder_output = layers.GlobalMaxPooling2D()(x)

print("Creating a model using the layers")
encoder = keras.Model(encoder_input, encoder_output, name="encoder")
print("More information about the model")
encoder.summary()

decoder_input = keras.Input(shape=(16,), name="encoded_img")
print("Reshaping the layers in the model")
x = layers.Reshape((4, 4, 1))(decoder_input)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
x = layers.Conv2DTranspose(32, 3, activation="relu")(x)
x = layers.UpSampling2D(3)(x)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
decoder_output = layers.Conv2DTranspose(1, 3, activation="relu")(x)
print("Creating a model using the layers")
decoder = keras.Model(decoder_input, decoder_output, name="decoder")
print("More information about the model")
decoder.summary()

autoencoder_input = keras.Input(shape=(28, 28, 1), name="img")
encoded_img = encoder(autoencoder_input)
decoded_img = decoder(encoded_img)
autoencoder = keras.Model(autoencoder_input, decoded_img, name="autoencoder")
print("More information about the model")
autoencoder.summary()

코드 출처 — https://www.tensorflow.org/guide/keras/functional

실행 결과

original_img (InputLayer)     [(None, 28, 28, 1)]        0
_________________________________________________________________
conv2d_28 (Conv2D)            (None, 26, 26, 16)         160
_________________________________________________________________
conv2d_29 (Conv2D)            (None, 24, 24, 32)         4640
_________________________________________________________________
max_pooling2d_7 (MaxPooling2  (None, 8, 8, 32)           0
_________________________________________________________________
conv2d_30 (Conv2D)            (None, 6, 6, 32)           9248
_________________________________________________________________
conv2d_31 (Conv2D)            (None, 4, 4, 16)           4624
_________________________________________________________________
global_max_pooling2d_3        (Glob (None, 16)           0
=================================================================
Total params: 18,672
Trainable params: 18,672
Non-trainable params: 0
_________________________________________________________________
Reshaping the layers in the model
Creating a model using the layers
More information about the model
Model: "decoder"
_________________________________________________________________
Layer (type)                  Output Shape               Param #
=================================================================
encoded_img (InputLayer)      [(None, 16)]               0
_________________________________________________________________
reshape_1 (Reshape)           (None, 4, 4, 1)            0
_________________________________________________________________
conv2d_transpose_4 (Conv2DTr  (None, 6, 6, 16)           160
_________________________________________________________________
conv2d_transpose_5 (Conv2DTr  (None, 8, 8, 32)           4640
_________________________________________________________________
up_sampling2d_1 (UpSampling2  (None, 24, 24, 32)         0
_________________________________________________________________
conv2d_transpose_6 (Conv2DTr  (None, 26, 26, 16)         4624
_________________________________________________________________
conv2d_transpose_7 (Conv2DTr  (None, 28, 28, 1)          145
=================================================================
Total params: 9,569
Trainable params: 9,569
Non-trainable params: 0
_________________________________________________________________
More information about the model
Model: "autoencoder"
_________________________________________________________________
Layer (type)                Output Shape                Param #
=================================================================
img (InputLayer)            [(None, 28, 28, 1)]         0
_________________________________________________________________
encoder (Functional)        (None, 16)                  18672
_________________________________________________________________
decoder (Functional)        (None, 28, 28, 1)           9569
=================================================================
Total params: 28,241
Trainable params: 28,241
Non-trainable params: 0
_________________________________________________________________

코드 설명

  • 모든 Keras 모델은 다른 레이어의 '입력(input)' 또는 출력에 대해 호출함으로써 하나의 레이어처럼 취급할 수 있습니다.
  • 모델을 호출하면 해당 모델의 아키텍처가 그대로 재사용됩니다.
  • 아키텍처뿐만 아니라 모델이 학습한 가중치(weight) 역시 함께 재사용됩니다.
  • 오토인코더 모델은 인코더 모델과 디코더 모델을 조합하여 만들 수 있습니다.
  • 두 모델을 두 번의 호출로 서로 연결(chaining)하면 완전한 오토인코더 모델이 완성됩니다.