블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2018. 7. 11. 15:08 AI Deep Learning/NN by Sung Kim

Class, tf.layers, Ensemble 강좌를 정리한다.




Python Class로 관리하기 


파이썬의 클래스로 만들어 사용하자. 복잡한 layer를 만들 때 사용하자.



예제

class Model:


    def __init__(self, sess, name):

        self.sess = sess

        self.name = name

        self._build_net()


    def _build_net(self):

        with tf.variable_scope(self.name):

            # dropout (keep_prob) rate  0.7~0.5 on training, but should be 1

            # for testing

            self.keep_prob = tf.placeholder(tf.float32)


            # input place holders

            self.X = tf.placeholder(tf.float32, [None, 784])

            # img 28x28x1 (black/white)

            X_img = tf.reshape(self.X, [-1, 28, 28, 1])

            self.Y = tf.placeholder(tf.float32, [None, 10])


            # L1 ImgIn shape=(?, 28, 28, 1)

            W1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01))

            #    Conv     -> (?, 28, 28, 32)

            #    Pool     -> (?, 14, 14, 32)

            L1 = tf.nn.conv2d(X_img, W1, strides=[1, 1, 1, 1], padding='SAME')

            L1 = tf.nn.relu(L1)

            L1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1],

                                strides=[1, 2, 2, 1], padding='SAME')

            L1 = tf.nn.dropout(L1, keep_prob=self.keep_prob)

            '''

            Tensor("Conv2D:0", shape=(?, 28, 28, 32), dtype=float32)

            Tensor("Relu:0", shape=(?, 28, 28, 32), dtype=float32)

            Tensor("MaxPool:0", shape=(?, 14, 14, 32), dtype=float32)

            Tensor("dropout/mul:0", shape=(?, 14, 14, 32), dtype=float32)

            '''


            # L2 ImgIn shape=(?, 14, 14, 32)

            W2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))

            #    Conv      ->(?, 14, 14, 64)

            #    Pool      ->(?, 7, 7, 64)

            L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME')

            L2 = tf.nn.relu(L2)

            L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1],

                                strides=[1, 2, 2, 1], padding='SAME')

            L2 = tf.nn.dropout(L2, keep_prob=self.keep_prob)

            '''

            Tensor("Conv2D_1:0", shape=(?, 14, 14, 64), dtype=float32)

            Tensor("Relu_1:0", shape=(?, 14, 14, 64), dtype=float32)

            Tensor("MaxPool_1:0", shape=(?, 7, 7, 64), dtype=float32)

            Tensor("dropout_1/mul:0", shape=(?, 7, 7, 64), dtype=float32)

            '''


            # L3 ImgIn shape=(?, 7, 7, 64)

            W3 = tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.01))

            #    Conv      ->(?, 7, 7, 128)

            #    Pool      ->(?, 4, 4, 128)

            #    Reshape   ->(?, 4 * 4 * 128) # Flatten them for FC

            L3 = tf.nn.conv2d(L2, W3, strides=[1, 1, 1, 1], padding='SAME')

            L3 = tf.nn.relu(L3)

            L3 = tf.nn.max_pool(L3, ksize=[1, 2, 2, 1], strides=[

                                1, 2, 2, 1], padding='SAME')

            L3 = tf.nn.dropout(L3, keep_prob=self.keep_prob)


            L3_flat = tf.reshape(L3, [-1, 128 * 4 * 4])

            '''

            Tensor("Conv2D_2:0", shape=(?, 7, 7, 128), dtype=float32)

            Tensor("Relu_2:0", shape=(?, 7, 7, 128), dtype=float32)

            Tensor("MaxPool_2:0", shape=(?, 4, 4, 128), dtype=float32)

            Tensor("dropout_2/mul:0", shape=(?, 4, 4, 128), dtype=float32)

            Tensor("Reshape_1:0", shape=(?, 2048), dtype=float32)

            '''


            # L4 FC 4x4x128 inputs -> 625 outputs

            W4 = tf.get_variable("W4", shape=[128 * 4 * 4, 625],

                                 initializer=tf.contrib.layers.xavier_initializer())

            b4 = tf.Variable(tf.random_normal([625]))

            L4 = tf.nn.relu(tf.matmul(L3_flat, W4) + b4)

            L4 = tf.nn.dropout(L4, keep_prob=self.keep_prob)

            '''

            Tensor("Relu_3:0", shape=(?, 625), dtype=float32)

            Tensor("dropout_3/mul:0", shape=(?, 625), dtype=float32)

            '''


            # L5 Final FC 625 inputs -> 10 outputs

            W5 = tf.get_variable("W5", shape=[625, 10],

                                 initializer=tf.contrib.layers.xavier_initializer())

            b5 = tf.Variable(tf.random_normal([10]))

            self.logits = tf.matmul(L4, W5) + b5

            '''

            Tensor("add_1:0", shape=(?, 10), dtype=float32)

            '''


        # define cost/loss & optimizer

        self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(

            logits=self.logits, labels=self.Y))

        self.optimizer = tf.train.AdamOptimizer(

            learning_rate=learning_rate).minimize(self.cost)


        correct_prediction = tf.equal(

            tf.argmax(self.logits, 1), tf.argmax(self.Y, 1))

        self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


    def predict(self, x_test, keep_prop=1.0):

        return self.sess.run(self.logits, feed_dict={self.X: x_test, self.keep_prob: keep_prop})


    def get_accuracy(self, x_test, y_test, keep_prop=1.0):

        return self.sess.run(self.accuracy, feed_dict={self.X: x_test, self.Y: y_test, self.keep_prob: keep_prop})


    def train(self, x_data, y_data, keep_prop=0.7):

        return self.sess.run([self.cost, self.optimizer], feed_dict={

            self.X: x_data, self.Y: y_data, self.keep_prob: keep_prop})








Layer API


conv2d: convolution layer

dense: fully conntected

예제








Ensemble 사용하기 


여러개를 조합해서 조화롭게 만든다. 여러개의 독립된 Model을 training시키고, 각 예측을 조합하여 최종 결과를 만든다. 





Ensemble Training 하기


- Model을 만든다

- 각각의 독립된 Model 을 꺼내와서 학습을 시킨다. 




각각의 합치는 것으로 조화롭게 만들어 본다.  결과 중 가장 높은 값을 선택한다.




Tensorflow 코드에서 prediction은 최종 결과의 값들이다. 정확도가 0.9952 까지 올라간다. 







참조


- 김성훈 교수님의 Class, tf.layers, Ensemble 강좌

'AI Deep Learning > NN by Sung Kim' 카테고리의 다른 글

[RNN] Basic & Training 하기  (0) 2018.07.11
[RNN] Recurrent Neural Network 개념  (0) 2018.07.11
[CNN] MNIST 99% 도전  (0) 2018.07.11
[CNN] Tensorflow CNN 기본  (0) 2018.07.11
[CNN] Convolution Neural Network  (0) 2018.07.10
posted by 윤영식
2018. 7. 11. 14:53 AI Deep Learning/NN by Sung Kim

MNIST 99% 도전 강좌를 정리한다. 






Simple CNN Tensorflow 코딩


Convolution Layer 2개와 Fully-conntect Layer를 코딩한다. 




Conv layer 1 만들기


- 784 개 값을 가진다. None 은 n개 이미지

- reshape 28x28x1로 만듦

- X image가 입력

- filter 3x3x1 로 하고, 32개 filter를 만듦

- filter의 stride 1 로 한다. 

- L1  출력은 input image사이즈가 동일하게 나옴 (padding SAME)

- relu 통과 시킨후 max_pooling한다. 2 stride 여서 최종결과는 14x14x32 로 나옴



Conv layer 2 만들기 


- 14x14x32 최종결과를 입력으로 사용한다.

- 64 개 filter를 사용한다. 1 stride 사용

- relu 사용하고 max_pool통과 한다. 2 stride 이므로 size는 7x7x64가 된다. 

- Fully conntected 넣기 전에 reshape 한다. 최종 3136 개가 된다.  





Fully Connected (FC, Dense) Layer 만들기 


- hypothesis를 만든다. 




학습(Learning) 시키고 테스트하기 


- 에폭(epoch) 단위로 학습 

- cost, optimizer를 수행

- 0, 1을 true, false로 나누어 계산

- 정확도: 0.9885







더 많은 Conv Layers


Conv layer 3개 FC 2개를 사용한다. 




- 정확도: 0.9938 로 높아진다. 

- dropout은 학습시 0.5~0.7 로 테스트시에는 1로 해야 한다. 






참조


- 김성훈교수님의 MNIST 99% 도전 강좌

posted by 윤영식
2018. 7. 11. 14:31 AI Deep Learning/NN by Sung Kim

Tensorflow CNN 기본 강좌를 정리한다. 





CNN 정리


Image와 Text 인식에 특출하다

- Convolution layer를 만들고

- pool sampling을 하고 

- 특징을 뽑아내고 (feature extraction)

- FF 로 classification 한다. 



예) 3x3x1 image에서 2x2x1 filter 로 맨뒤 이미지와 같은 색 1을 갖는다. filter가 stride가 움직이며 1개의 값을 뽑아낸다. ]






Tensorflow 코드 이해


[1, 3, 3, 1] : 맨 앞은 한개의 이미지만을 사용하겠다. 3x3x1 의 image를 시각화 하면 imshow를 사용해 만들 수 있다. 



이것을 Simple Convolution layer로 만들어 시각화 하면

- filter size만큼 안에 있는 것을 더 함.




- stride가 1만큼 움직이며 다음 값을 더 함. 




Convolution을 직접 그리지 않고 Tensorflow 수식으로 표현할 때 conv2d를 사용한다.







Padding


SAME: convolution layer를 실제 image와 같은 사이즈가 되게 만든다.  즉, INPUT과 OUTPUT size를 같게한다. 



Tensorflow로 구현하면 



Filter를 여러개 사용할 경우, 1장의 image로 부터 3장의 filter 이미지가 나온다. 







Max Pooling


데이터를 줄여서 sub sampling을 하는 것이다. max_pool을 사용한다. max_pool이 CNN가 잘 동작한다. 







실제 이미지로 테스트 하기 


데이터를 읽어오고, 28x28 사이즈의 image를 읽는다. 



Convolution Layer를 만든다. 

-  -1은 n개의 image 읽음. 3x3 filter size, 5개 filter 사용, 2 stride, SAME padding

- filter 5개 이므로 이미지가 5개 이다. 2 stride 여서 결과는 14x14 이다.




max pooling을 수행한다. 14x14에 대한 2 stride를 하면 결과는 7x7이 나온다. 이미지가 sub sampling되어 이미지 해상도가 떨어져 있다.






참조


- 김성훈교수님의 Tensorflow CNN 기본 강좌

'AI Deep Learning > NN by Sung Kim' 카테고리의 다른 글

[CNN] Class, tf.layers, Ensemble  (0) 2018.07.11
[CNN] MNIST 99% 도전  (0) 2018.07.11
[CNN] Convolution Neural Network  (0) 2018.07.10
[Neural Network] Softmax에 NN 적용하는 순서 팁  (0) 2018.07.09
[Neural Network] 종류  (0) 2018.07.09
posted by 윤영식
2018. 7. 10. 16:56 AI Deep Learning/NN by Sung Kim

Convolutional Neural Network 강좌를 정리한다.





Convolutional Neural Network


하나의 입력이 계속 여러개인 경우는 fully Connected Network 이고 여러 입력 Layer를 가지고 있는 경우를 CNN이라 한다. 



CNN은 고양이가 이미지를 받아들이는 것이 한조각씩 나누어서 인지하고 이것을 합치는 실험에서 출발한다. 





CNN 처리과정


일정 부분을 처리하는 것을 filter라 부른다. 예로 32x32x3 image를 5x5x3 사이즈로 필터링한다. 그러면서 이 작은 이미지를 전체 이미지를 이동하며 Wx+b를 수행한다. 



이것을 이동해 가는 것을 그림으로 그려본다. 한칸을 Stride라고 한다. 2 stride는 두칸이 이동함을 의미한다. 



CNN을 사용할 때는 pad(모서리) 라는 개념을 사용함. 7x7 에 패딩을 줌으로 9x9가 된다. 하지만 INPUT과 OUTPUT은 7x7로 같아진다. 







Max Pooling 


pool을 sampling이라고 보면된다. 


각 한 Layer에 대해 크기를 줄여서 sampling한다. max pooling은 layer안에서 가장 큰값을 고르는 것이다. 



CONV -> ReLU -> POOL ==> 최종: FC (Fully Connected Layer)




ConvNet 활용 예


라쿤 교수의 LeNet




AlexNet


처음  ReLU사용 in ImageNet



GoogLeNet


2014년에 시도 



ResNet


2015년에 나옴. 많은 대회를 휩쓸면서 최강좌 자리차지함. 152 Layer를 사용한다. Fast Forward를 사용하여 학습하는 Layer를 줄여줌.





2014년 Yoon Kim 


Text에 대한 Classification이 가능해짐




그리고 CNN을 사용한 DeepMind사의 알파고가 있다. 





참조


김성훈교수님의 CNN 소개 강좌활용 예 강좌

ConvNetJS 데모를 통해 시각화



'AI Deep Learning > NN by Sung Kim' 카테고리의 다른 글

[CNN] MNIST 99% 도전  (0) 2018.07.11
[CNN] Tensorflow CNN 기본  (0) 2018.07.11
[Neural Network] Softmax에 NN 적용하는 순서 팁  (0) 2018.07.09
[Neural Network] 종류  (0) 2018.07.09
[Deep Learning] Dropout 과 앙상블  (0) 2018.07.09
posted by 윤영식

NN의 MNIST 98% 이상 올리기 강좌를 정리한다. 





일반 Softmax MNIST 예


정확도: 0.9035

softmax에 대한 개념 정리를 참조하면 Softmax는 결과 Label을 모두 합치면 1되도록 0과 1사이의 값으로 나오게 한다. 확률(Probability) 의미








일반 Softmax를 NN으로 구성하기 


정확도: 0.9455

Neural Network Layer를 3단 정도 구성해 준다. 이때 ReLU를 사용한다. 






Xavier사용한 초기화 잘 하기


정확도: 0.9783

샤비어(Xavier)를 적용한다. 구글 검색 "Xavier Initialization Tensorflow" . Xavier를 쓰면 처음부터 Cost값이 상당히 낮다. 이것은 초기값을 잘 썼음을 나타낸다. 


모델은 바꾸지 않고 초기값만 바꾸었을 때의 비교






깊고 넓게 적용할 때 Dropout 사용하기


정확도: 0.9804

깊게 사용시 중간의 값을 더 많이 쓴다. Overfitting이 발생할 수 있으므로 Dropout으로 이를 예방한다. 한 Layer에 대해 Dropout을 한다. 

dropout하지 않고 깊고 넓게 했을 때, 정확도가 0.9783보다 낮게 나온다. 네트워크가 깊어지면 학습된 것을 모두 기억해서 나중에 overfitting을 일을킬 수 있다. 이경우는 정확도가 낮아져서 Overfitting된 것이다. 



dropout시 몇 %를 Keep (학습 내용을 기억)할 것인지 - keep probability - 은 0.5~0.7 을 사용한다. 단, 테스트할 때는 1을 사용한다. 







Adam Optimizer 사용하기


기존은 GradientDescentOptimizer를 사용하였다. 여러 종류의 Optimizer가 있다.



ADAM이 Cost를 빠르게 감소시켜준다. 



공식






결론


최근은 입력값을 Normalization을 잘 하는 것도 사용한다. 



CNN을 사용하게 되면 Accuracy가 99%까지 올라간다. 






참조


- 김성훈교수님의 NN의 98% 정확도 올리기 강좌

- Xavier Initialization Tensorflow 구글 검색 첫번째

- Softmax 정리글 (강추)

'AI Deep Learning > NN by Sung Kim' 카테고리의 다른 글

[CNN] Tensorflow CNN 기본  (0) 2018.07.11
[CNN] Convolution Neural Network  (0) 2018.07.10
[Neural Network] 종류  (0) 2018.07.09
[Deep Learning] Dropout 과 앙상블  (0) 2018.07.09
[Deep Learning] Weight 초기화 잘하기  (0) 2018.07.09
posted by 윤영식

레고처럼 넷트웍 모듈 만들기 강좌를 정리한다. 





Fast Foward


이전 Layer의 결과를 n layer 앞읠 input값으로 사용한다. 예) 2015년도 Image Net




Split & Merge


나누어서 합치거나, 처음부터 나누어서 나중에 합침등





Recurrent network


밑에서 위로 가면서 옆으로도 확장됨



오직 개발자의 상상력으로 CNN, RNN, FF등을 사용하여 NN을 구축해서 할 뿐이다.





참조


- 김성훈교수님의 네트웍 모듈 만들기 강좌

- Machine Learning 용어 정리

posted by 윤영식
prev 1 next