티스토리 뷰

Deep Neural Network in TensorFlow

 - 텐서플로우를 사용하여 logistic classifier를 구현해봤었는데, 이번엔 Deep neural network를 구현해보도록 하자.

 - MNIST 데이터베이스의 문자들을 분류하기위해 작성된 텐서플로우 코드를 가지고 구현을 진행한다.

 - 여기에서 텐서플로우의 다른 예제들을 확인




TensorFlow MNIST

1
2
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(".", one_hot=True, reshape=False)
cs

 - 텐서플로우에서 제공하는 MNIST 데이터셋을 사용하여 진행한다.

 - 이 데이터셋은 batch들과 One-Hot encode 들로 구성이 되어있음.




Learning Parameters

1
2
3
4
5
6
7
8
9
10
import tensorflow as tf
 
# Parameters
learning_rate = 0.001
training_epochs = 20
batch_size = 128  # Decrease batch size if you don't have enough memory
display_step = 1
 
n_input = 784  # MNIST data input (img shape: 28*28)
n_classes = 10  # MNIST total classes (0-9 digits)
cs

 - 매개변수의 튜닝(tuning)이 아닌 multi-layer neural network 신경망의 아키텍처를 중점적으로 진행해보자.

 - 따라서 적절한 인자들에 대한 값을 위와같이 명시해두고 진행해나가자.




Hidden Layer Parameters

1
n_hidden_layer = 256 # layer number of features
cs

 - 위와같이 hidden layer의 크기를 정할 수 있다.

 - 이를 레이어의 너비(width of a layer)라고도 부른다.




Weights and Biases

1
2
3
4
5
6
7
8
9
# Store layers weight & bias
weights = {
    'hidden_layer': tf.Variable(tf.random_normal([n_input, n_hidden_layer])),
    'out': tf.Variable(tf.random_normal([n_hidden_layer, n_classes]))
}
biases = {
    'hidden_layer': tf.Variable(tf.random_normal([n_hidden_layer])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}
cs

 - Deep neural network는 다수의 레이어 각각마다 다른 가중치와 바이어스를 적용한다.

 - 위의 코드에서는 hidden layer의 weights와 bias가, output layer의 weights와 bias를 할당하고 있다.

 - 만약 신경망 네트워크가 더 심화(deeper)될 수록 즉, 레이어가 더 추가될 수록

 - 각각의 레이어에 따로 weights와 bias가 할당되게 된다.






Input

1
2
3
4
5
# tf Graph input
= tf.placeholder("float", [None, 28281])
= tf.placeholder("float", [None, n_classes])
 
x_flat = tf.reshape(x, [-1, n_input])
cs

 - MNIST 데이터는 단일 채널에 28 * 28 픽셀의 이미지로 구성이 된다.

 - tf.reshape() 함수는 x의 28px by 28px의 행렬을 784픽셀의 행벡터로 재구현한다.






Multilayer Perceptron

1
2
3
4
5
6
# Hidden layer with RELU activation
layer_1 = tf.add(tf.matmul(x_flat, weights['hidden_layer']),\
    biases['hidden_layer'])
layer_1 = tf.nn.relu(layer_1)
# Output layer with linear activation
logits = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])
cs

 - 이전에 linear function에 대해 다룰 때 wx + b 꼴로 다뤘었는데, 

 - ReLU에 linear function을 같이 사용해주면 두개의 레이어의 네트워크를 구현할 수 있다.




Optimizer

1
2
3
4
5
# Define loss and optimizer
cost = tf.reduce_mean(\
    tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\
    .minimize(cost)
cs

 - 위의 optimization 기술은 이전에 lab때 다뤘던 것과 동일하다.




Session

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Initializing the variables
init = tf.global_variables_initializer()
 
 
# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    # Training cycle
    for epoch in range(training_epochs):
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
cs

 - 텐서플로우의 MNIST라이브러리는 각 batch당 데인터셋을 일괄적으로 받아올 수 있도록 해준다.

 - mnist.train.next_batch() 함수를 사용하면 학습된 데이터의 하위집합이 리턴된다.




 - 이렇게 layer들을 추가하여 Deeper Neural Network를 구현하면 

 - 더 복잡한 문제들을 해결하는 네트워크를 구현할 수 있다.


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/03   »
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
글 보관함