NeuroWhAI의 잡블로그

[TensorFlow] 오토인코더 본문

개발 및 공부/라이브러리&프레임워크

[TensorFlow] 오토인코더

NeuroWhAI 2018. 1. 22. 20:06


이번 챕터는 뭔가 허무한 느낌이 있네요 ㅠㅠ
오토인코더 구현하고 끝이라니...
추출한 특징을 쓰는 것까지 했으면 좋았을 텐데 아쉽네요.

(기초적인) 오토인코더는 입력 X와 출력 Y가 있을때 출력 Y를 X와 똑같이 만드는 방법으로 특징을 추출한다고 합니다.
단, 히든 레이어를 입력 레이어의 뉴런 개수보다 작게 배치함으로써 데이터를 압축하게 됩니다.
(오히려 더 많이 배치하고 어떠한 제한을 걸어서 특징을 추출하기도 한답니다.)

코드:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#-*- coding: utf-8 -*-
 

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
 
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data/", one_hot=True)
 
learning_rate = 0.01
training_epoch = 20
batch_size = 100
n_hidden = 256
n_input = 28*28
 
= tf.placeholder(tf.float32, [None, n_input])
 
W_encode = tf.Variable(tf.random_normal([n_input, n_hidden]))
b_encode = tf.Variable(tf.random_normal([n_hidden]))
 
encoder = tf.nn.sigmoid(tf.add(tf.matmul(X, W_encode), b_encode))
 
W_decode = tf.Variable(tf.random_normal([n_hidden, n_input]))
b_decode = tf.Variable(tf.random_normal([n_input]))
 
decoder = tf.nn.sigmoid(tf.add(tf.matmul(encoder, W_decode), b_decode))
 
cost = tf.reduce_mean(tf.pow(X - decoder, 2))
 
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
 
    total_batch = int(mnist.train.num_examples / batch_size)
 
    for epoch in range(training_epoch):
        total_cost = 0
 
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
 
            _, cost_val = sess.run([optimizer, cost],
                feed_dict={X: batch_xs})
 
            total_cost += cost_val
 
        print('Epoch:''%04d' % (epoch + 1),
            'Avg. cost =''{:.4f}'.format(total_cost / total_batch))
 
    print('완료!')
 
    sample_size = 10
 
    samples = sess.run(decoder,
        feed_dict={X: mnist.test.images[:sample_size]})
 
    fig, ax = plt.subplots(2, sample_size, figsize=(sample_size, 2))
 
    for i in range(sample_size):
        ax[0][i].set_axis_off()
        ax[1][i].set_axis_off()
        ax[0][i].imshow(np.reshape(mnist.test.images[i], (2828)))
        ax[1][i].imshow(np.reshape(samples[i], (2828)))
 
    plt.show()
 
    

결과:

Epoch: 0001 Avg. cost = 0.2079
Epoch: 0002 Avg. cost = 0.0646
Epoch: 0003 Avg. cost = 0.0562
Epoch: 0004 Avg. cost = 0.0497
Epoch: 0005 Avg. cost = 0.0446
Epoch: 0006 Avg. cost = 0.0414
Epoch: 0007 Avg. cost = 0.0384
Epoch: 0008 Avg. cost = 0.0367
Epoch: 0009 Avg. cost = 0.0356
Epoch: 0010 Avg. cost = 0.0342
Epoch: 0011 Avg. cost = 0.0339
Epoch: 0012 Avg. cost = 0.0335
Epoch: 0013 Avg. cost = 0.0333
Epoch: 0014 Avg. cost = 0.0323
Epoch: 0015 Avg. cost = 0.0320
Epoch: 0016 Avg. cost = 0.0318
Epoch: 0017 Avg. cost = 0.0314
Epoch: 0018 Avg. cost = 0.0313
Epoch: 0019 Avg. cost = 0.0311
Epoch: 0020 Avg. cost = 0.0308
완료!


사진의 위쪽이 원본 입력이고 출력이 인코딩 후 디코딩된 이미지 입니다.
뭔가 노이즈가 있는데 뭘까요..

코드는 이전 예제들에 비하면 간단합니다.
28*28 -> 256 -> 28*28 모양의 신경망입니다.
활성화 함수로 시그모이드를 사용했고
비용 함수로는 단순하게 입력과 출력 차이의 제곱 평균 입니다.

... 이게 다네요.
어떻게 응용하는지 정도는 알려주시지 ㅠㅠ
히든 레이어의 출력을 새로운 입력으로 써야하는지 디코더의 출력을 새로운 입력으로 써야하는지 모르겠네요.
전자가 맞을것 같은뎅.




Comments