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

파이썬과 케라스로 인코더·디코더 기반 오토인코더 구축하는 방법

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

윈도우 환경에서는 아래 명령어 한 줄로 'tensorflow' 패키지를 설치할 수 있습니다.

pip install tensorflow

텐서(Tensor)는 TensorFlow에서 사용되는 핵심 데이터 구조입니다. 텐서는 데이터 흐름 그래프(Data Flow Graph)의 노드를 연결하는 역할을 하며, 본질적으로 다차원 배열 또는 리스트라고 할 수 있습니다.

케라스(Keras)란?

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

Keras는 TensorFlow 패키지에 이미 포함되어 있어, 아래 코드로 간단히 불러올 수 있습니다.

import tensorflow
from tensorflow import keras

함수형 API(Functional API)의 장점

케라스의 함수형 API는 순차형(Sequential) API보다 훨씬 유연한 모델 생성을 가능하게 합니다. 비선형 토폴로지를 가진 모델을 다룰 수 있고, 레이어를 공유하거나 여러 입력과 출력을 처리할 수 있습니다. 일반적으로 딥러닝 모델은 여러 레이어로 구성된 방향성 비순환 그래프(DAG, Directed Acyclic Graph)이며, 함수형 API는 이러한 레이어 그래프를 손쉽게 구축할 수 있도록 도와줍니다.

이번 예제는 Google Colaboratory(Colab)에서 실행했습니다. Colab은 브라우저에서 파이썬 코드를 실행할 수 있게 해주며, 별도의 설정 없이 GPU에 무료로 접근할 수 있다는 장점이 있습니다. Jupyter Notebook을 기반으로 만들어졌습니다.

오토인코더 구현 예제

아래 코드는 인코더와 디코더를 결합하여 오토인코더를 생성하는 과정을 보여줍니다.

encoder_input = keras.Input(shape=(28, 28, 1), name="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()

print("Reshaping the layers in the model")
x = layers.Reshape((4, 4, 1))(encoder_output)
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)

autoencoder = keras.Model(encoder_input, decoder_output, name="autoencoder")
print("More information about the autoencoder")
autoencoder.summary()

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

실행 결과

Adding layers to the model
Performing global max pooling
Creating a model using the layers
More information about the model
Model: "encoder"
_________________________________________________________________
Layer (type)                Output Shape              Param #
=================================================================
img (InputLayer)            [(None, 28, 28, 1)]       0
_________________________________________________________________
conv2d (Conv2D)             (None, 26, 26, 16)        160
_________________________________________________________________
conv2d_1 (Conv2D)           (None, 24, 24, 32)        4640
_________________________________________________________________
max_pooling2d (MaxPooling2D)(None, 8, 8, 32)          0
_________________________________________________________________
conv2d_2 (Conv2D)           (None, 6, 6, 32)          9248
_________________________________________________________________
conv2d_3 (Conv2D)           (None, 4, 4, 16)          4624
_________________________________________________________________
global_max_pooling2d (Global (None, 16)               0
=================================================================
Total params: 18,672
Trainable params: 18,672
Non-trainable params: 0
_________________________________________________________________
Reshaping the layers in the model
More information about the autoencoder
Model: "autoencoder"
_________________________________________________________________
Layer (type)                Output Shape              Param #
=================================================================
img (InputLayer)            [(None, 28, 28, 1)]       0
_________________________________________________________________
conv2d (Conv2D)             (None, 26, 26, 16)        160
_________________________________________________________________
conv2d_1 (Conv2D)           (None, 24, 24, 32)        4640
_________________________________________________________________
max_pooling2d (MaxPooling2D)(None, 8, 8, 32)          0
_________________________________________________________________
conv2d_2 (Conv2D)           (None, 6, 6, 32)          9248
_________________________________________________________________
conv2d_3 (Conv2D)           (None, 4, 4, 16)          4624
_________________________________________________________________
global_max_pooling2d (Global (None, 16)               0
_________________________________________________________________
reshape (Reshape)           (None, 4, 4, 1)           0
_________________________________________________________________
conv2d_transpose (Conv2DTran (None, 6, 6, 16)         160
_________________________________________________________________
conv2d_transpose_1 (Conv2DTr (None, 8, 8, 32)         4640
_________________________________________________________________
up_sampling2d (UpSampling2D) (None, 24, 24, 32)       0
_________________________________________________________________
conv2d_transpose_2 (Conv2DTr (None, 26, 26, 16)       4624
_________________________________________________________________
conv2d_transpose_3 (Conv2DTr (None, 28, 28, 1)        145
=================================================================
Total params: 28,241
Trainable params: 28,241
Non-trainable params: 0
_________________________________________________________________

코드 설명

  • 모델에 Conv2D, MaxPooling2D 등의 레이어가 순차적으로 추가됩니다.
  • 레이어 스택에 전역 최대 풀링(Global Max Pooling)이 적용되어 인코더 출력이 생성됩니다.
  • 정의된 입출력을 바탕으로 하나의 모델(encoder)이 생성됩니다.
  • 'summary()' 메서드를 호출하면 모델의 구조와 파라미터 정보를 확인할 수 있습니다.
  • 함수형 API에서는 레이어 그래프(graph-of-layers)의 입력과 출력을 지정한 후 모델을 생성합니다.
  • 즉, 하나의 레이어 그래프를 재사용하여 여러 개의 모델을 만들 수 있습니다.
  • 이 예제에서는 동일한 레이어 스택으로 두 가지 모델을 인스턴스화했습니다. 이미지 입력을 16차원 벡터로 변환하는 인코더와, 학습에 사용되는 오토인코더입니다.