본문 바로가기

AI/이론

[ML] AutoEncoder

또한, 오토인코더는 reduction 측면과, reconstructing 측면이 함께 학습되며, 압축된 data coding을 통해서 실제 입력과 최대한 가까운 결과를 생성하기 때문에 Generative Model의 역할도 수행할 수 있습니다.

 

위 내용을 토대로 위키피디아에서 오토인코더의 키워드는 다음과 같습니다.

Keword

- Unsupervised learning

- Representation learning (= Efficient coding learning)

- Dimensionality reduction

- Generative model learning

 

주로 오토인코더는 Dimensionality reduction, 차원 축소를 위해서 많이 사용됩니다.

오토인코더의 차원축소는 정확히 말하면 Nonlinear Dimensionality Reduction이며, 이는 Representation learning / Efficient coding learning / Feature extraction / Manifold learning과 동일한 의미입니다.

 

최종적으로 정리를 하면, 오토인코더는 다음과 같은 4개의 주요 키워드가 있습니다.

오토인코더가 학습할 때,

비교사 학습 방법(Unsupervised learning)으로 학습하고, Loss는 negative ML(ML density estimation)으로 해석되고,

학습된 오토인코더에서,

인코더는 차원 축소 역할을 수행(Manifold learning)하며, 디코더는 생성 모델의 역할(Generative model learning)을 수행합니다.



 

Reduction Dimension

차원 축소 방법에는 위와 같은 다양한 방법들이 존재합니다. 그중에 오토인코더는 Non-Linear에 속합니다.


오토인코더는 입출력이 동일한 네트워크입니다. 따라서 output layer는 input layer와 같은 크기를 갖습니다.

입출력이 동일한 네트워크이기 때문에 Loss는 output이 input과 얼마나 유사한지 비교하며,

Unsupervised learning을 supervised learning 문제로 바꿔서 해결합니다.


간단한 autoencoder

single fully-connected neural layer를 사용해서 만들어보겠습니다.

import tensorflow as tf
import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
# encoding dimension
encoding_dim = 32
input_img = Input(shape=(784,)) # 28*28
encoded = Dense(encoding_dim, activation='relu')(input_img)
decoded = Dense(784, activation='sigmoid')(encoded)
# autoencoder
autoencoder = Model(input_img, decoded)
# encoder
encoder = Model(input_img, encoded)
# decoder
encoded_input = Input(shape=(encoding_dim,))
decoded_layer = autoencoder.layers[-1]
decoder = Model(encoded_input, decoded_layer(encoded_input))
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

사용될 mnist data는 28*28 사이즈의 이미지이므로, 28x28=784로 펼쳐서 입력으로 받습니다. 그리고 hidden layer는 32개의 unit으로 구성됩니다. 여기까지가 encoder의 역할이고, 이제 encoding한 데이터를 다시 784로 디코딩하는 decoder layer를 구성합니다.

 

autoencoder는 encoder와 decoder가 합쳐진 모델이며, 각각의 모델도 구성해둡니다.

 

그리고 데이터를 받고, 0~1 사이의 값으로 normalization을 해주고, 28x28이미지를 784의 크기의 벡터로 만들어줍니다.

autoencoder.fit(x_train_flatten, x_train_flatten,
batch_size=256, epochs=50,
validation_data=(x_test_flatten,x_test_flatten))

자기 자신이 target이다. 

Convolutional autoencoder

 

100 epoch 에서, train/test loss가 0.8까지 도달합니다. 이전 모델보다 훨씬 향상되었고, 이미지 또한 훨씬 선명해진 것 같습니다.

입력이 이미지이기 때문에 CNN 구조로 인코더/디코더를 구성할 수 있습니다. 실제로 이미지에 적용되는 autoencoder는 항상 convolutional autoencoder입니다. 성능이 더 좋기 때문이죠.

 

인코더는 Conv2D와 MaxPooling2D로 구성되고, 디코더는 Conv2D와 UpSampling2D로 구성됩니다.

그리고 입력이 (28, 28, 1)의 차원을 가지므로, 데이터의 차원을 변경해줍니다.

x_train = x_train.reshape((-1,28,28,1))
x_test = x_test.reshape((-1,28,28,1))
print(x_train.shape)
print(x_test.shape)
input_img = Input(shape=(28, 28, 1))  # 'channels_firtst'이미지 데이터 형식을 사용하는 경우 이를 적용
 
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
 
# encoder의 shape = (samples, 4, 4, 8)
 
x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
 
# decoder의 shape = (sampels, 28, 28, 1)
 
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
 
encoder = Model(input_img, encoded)
 
decoded_input = Input(shape=(4,4,8))
decoded_layer = autoencoder.layers[7](decoded_input)
for i in range(8,len(autoencoder.layers)):
    decoded_layer = autoencoder.layers[i](decoded_layer)
decoder = Model(decoded_input, decoded_layer)
 
from tensorflow.keras.callbacks import TensorBoard
autoencoder.fit(x_train, x_train, 
                batch_size=256, epochs=100, 
                validation_data=(x_test,x_test),
                callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])



 

AutoEncoder(오토인코더) - MNIST dataset 사용

MNIST dataset을 사용해서 여러 모델로 오토인코더를 구성해보았습니다. 내용은 아래 사이트를 참조하였습니다. keraskorea.github.io/posts/2018-10-23-keras_autoencoder/ 케라스로 이해하는 Autoencoder Buildi..

junstar92.tistory.com

 

 

 

AutoEncoder (1) : Maximum likelihood 관점에서의 해석

- Reference Slide : https://www.slideshare.net/NaverEngineering/ss-96581209 강의(youtube) : (1/3) https://www.youtube.com/watch?v=o_peo6U7IRM&ab_channel=naverd2 (2/3) https://www.youtube.com/watch?..

junstar92.tistory.com

 

'AI > 이론' 카테고리의 다른 글

[ML] Focal Loss  (0) 2022.12.08
[ML] DCN, Deformable Convolution Networks  (0) 2022.01.04
[ML] 분류 성능 평가 지표  (0) 2022.01.02
[ML] CNN의 역전파(backpropagation)  (0) 2021.12.30
[ML] Backpropagation  (0) 2021.12.30