티스토리 뷰

Neural Networks in Keras

 - 이전에 NumPy를 이용하여 네트워크를 설계하였다면, 이번엔 좀 더 실무적인 툴을 사용하여

 - 네트워크를 설계하는 방법에 대해 알아보자.

 - 툴을 사용하는 이유로는, activation function 이나 gradient descent 등을 직접 구현하지 않고

 - 가져다 쓰기만 해도 되는것이 단적인 예가 될 수 있겠다.

 - Keras, TensorFlow, Caffe, Theano, Scikit-learn 등의 툴이 이에 해당된다.

 - 이번시간에는 Keras를 다루는 법에대해 알아보자.




Building a Neural Networks in Keras

 - Keras를 사용하여 네트워크를 만들어가기 전에 알아야할 몇가지를 짚고 넘어가자.


 · Sequential Model

 - keras.models.Sequential 클래스는 sequence of layers 네트워크를 사용하기위환 wrapper class임

 - compile(), fit(), evaluate() 와 같은 메서드를 사용해서 Keras 모델 인터페이스를 구현하게 해줌.




 · Layers

 - Keras 의 Layer 클래스는 다양한 neural netwrok layers를 제공해줌

 - fully connected layers, max pool layers, activation layers 와 같은 레이어를 사용 가능.

 - 단순히 모델의 add() 함수만을 이용하여 레이어들을 사용 가능.


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
    import numpy as np
    from keras.models import Sequential
    from keras.layers.core import Dense, Activation
 
    # X has shape (num_rows, num_cols), where the training data are stored
    # as row vectors
    X = np.array([[00], [01], [10], [11]], dtype=np.float32)
 
    # y must have an output vector for each input vector
    y = np.array([[0], [0], [0], [1]], dtype=np.float32)
 
    # Create the Sequential model
    model = Sequential()
 
    # 1st Layer - Add an input layer of 32 nodes with the same input shape as
    # the training samples in X
    model.add(Dense(32, input_dim=X.shape[1]))
 
    # Add a softmax activation layer
    model.add(Activation('softmax'))
 
    # 2nd Layer - Add a fully connected output layer
    model.add(Dense(1))
 
    # Add a sigmoid activation layer
    model.add(Activation('sigmoid'))
cs




 - Keras는 첫번째 레이어에 입력 모양을 지정해야하지만, 

 - 다른 모든 레이어의 모양을 자동으로 추론한다.

 - 따라서 첫번째 레이어의 입력 크기(input dimensions)만을 명시해주면 된다.


 - 위의 첫번째(first, hidden) layer인 model.add(Dense(32, input_dim=X.shape[1]))

 - 를 보면, 2개의 element vectors를 input으로 하는 32개의 노드를 만들고 있다.

 - 각 레이어는 이전 레이어의 출력을 input으로 사용하고 pipe를 통해 다음 레이어로 전달한다.

 - 이 구조는 output 까지의 모든 레이어에 적용됨.

 - output은 1차원 (dimension 1)임을 확인할 수 있다.


 - Keras의 activation 레이어는 다음 두개의 방식이 동일하게 적용될 수 있다.

1
2
3

model.add(Dense(128)); model.add(Activation('softmax')) 
model.add(Dense(128, activation="softmax"))))
cs

 - 위의 두 코드는 완전히 동일하지만, 직접적인 접근을 용이하게 하기위해

 - 분리해서 작성하는것이 일반적이다. (특정 모델의 아키텍처에서 분리하는것이 유용하기 때문)




 - 모델을 빌드하고 나면 실행하기 전에 컴파일을 해야한다.

 - Keras 모델을 컴파일하면 백앤드(tensorflow, theano 등)를 호출하고, 

 - optimizer, loss function 등과 같이 모델이 실행되기 전에 필요한 다른 인자들을 결합한다.

 - 클래스가 두개인 경우에 loss function을 categorical_crossentropy로 지정하여 사용할 수 있으며

 - 이 경우 adam을 optimizer로 지정하게 된다(속도가 priority일 때의 디폴트값).

 - 마지막으로 모델과 함께 평가하려는 행렬(metrics)을 지정할 수 있다.

 - 이 때, 이 행렬을 통해 정확도를 지정할 수 있다.




 - 최종 모델을 위의 명령으로 확인 가능함.




 - 이 모델은 fit() 메서드에 의해 학습되는데, 위의 명령이 학습시킬 epoch의 수와 

 - 메세지 레벨(훈련중에 화면에 얼마나 많은 정보를 표현할 것인지)을 인자로 넣어줄 수 있다.

 - 참고로 Keras 1 에서는 nb_epoch가 epoch의 수를 나타내지만, Keras 2 에서는 epoches 가 이를 나타낸다.




 - 마지막으로 위 명령어를 통해 설계한 모델을 평가할 수 있다.






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
import numpy as np
from keras.utils import np_utils
import tensorflow as tf
# Using TensorFlow 1.0.0; use tf.python_io in later versions
tf.python.control_flow_ops = tf
 
# Set random seed
np.random.seed(42)
 
# Our data
= np.array([[0,0],[0,1],[1,0],[1,1]]).astype('float32')
= np.array([[0],[1],[1],[0]]).astype('float32')
 
# Initial Setup for Keras
from keras.models import Sequential
from keras.layers.core import Dense, Activation
 
# Building the model
xor = Sequential()
 
# Add required layers
xor.add(Dense(32, input_dim = 2))
xor.add(Activation('tanh'))
xor.add(Dense(1))
xor.add(Activation('sigmoid'))
 
# Specify loss as "binary_crossentropy", optimizer as "adam",
# and add the accuracy metric
xor.compile(loss = "binary_crossentropy", optimizer = "adam", metrics = ["accuracy"])
 
# Uncomment this line to print the model architecture
xor.summary()
 
# Fitting the model
history = xor.fit(X, y, nb_epoch=1000, verbose=0)
 
# Scoring the model
score = xor.evaluate(X, y)
print("\nAccuracy: ", score[-1])
 
# Checking the predictions
print("\nPredictions:")
print(xor.predict_proba(X))
cs

 - Keras를 이용한 간단한 네트워크 구현.

 - 참고 : https://github.com/keras-team/keras/blob/master/examples/mnist_mlp.py



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