오토인코더
import tensorflow as tf
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Dense
오토인코더
encoding_dim = 32
input_img = Input(shape=(784,))
encoded = Dense(encoding_dim, activation='relu')(input_img)
decoder_layer =decoded = Dense(784, activation='sigmoid')
decoded = decoder_layer(encoded)
autoencoder = Model(input_img, decoded)
인코더
encoder = Model(input_img, encoded)
디코더
encoded_input = Input(shape=(encoding_dim,))
decoder = tf.keras.Model(encoded_input, decoder_layer(encoded_input))
MNIST 데이터
import numpy as np
(x_train, y_train), (x_test, y_test) = \
tf.keras.datasets.mnist.load_data()
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
x_train = x_train.reshape((-1, 784))
x_test = x_test.reshape((-1, 784))
훈련
autoencoder.compile(loss='binary_crossentropy')
autoencoder.fit(x_train, x_train,
epochs=50,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test),
callbacks=[
tf.keras.callbacks.EarlyStopping(monitor='val_loss')])
원본에 노이즈 주입
x_test_noisy = x_test + np.random.normal(loc=0.0, scale=0.1, size=x_test.shape)
오토인코더에 인코딩 후 디코딩
encoded_imgs = encoder.predict(x_test_noisy)
decoded_imgs = decoder.predict(encoded_imgs)
시각화
import matplotlib.pyplot as plt
n = 10
plt.figure(figsize=(20, 6))
for i in range(n):
for j, img in enumerate([x_test, x_test_noisy, decoded_imgs]):
ax = plt.subplot(3, n, i + j * n + 1)
plt.imshow(img[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)