ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Keras] 튜토리얼2 - 하이퍼파라미터 튜닝이란?
    💫 Computer Science/Python & AI Framework 2019. 12. 12. 01:26

    ● 저번 포스팅 모델 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    from keras.models import Sequential
    from keras.layers import Dense
    import numpy as np
     
    = np.array([1,2,3,4,5])
    = np.array([1,2,3,4,5])
     
    model = Sequential()
    model.add(Dense(5, input_dim=1, activation='relu'))
    # input 1 output 5
    model.add(Dense(3))
    model.add(Dense(1))
     
    model.compile(loss='mse', optimizer='adam')
    model.fit(x, y, epochs=100, batch_size=1)
     
    loss, acc = model.evaluate(x, y, batch_size=1)
    print('acc : ', acc)
    cs

     

     

    ● 이번에 다룰 모델 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    from keras.models import Sequential
    from keras.layers import Dense
    import numpy as np
     
    = np.array([1,2,3,4,5,6,7,8,9,10])
    = np.array([1,2,3,4,5,6,7,8,9,10])
    x2 = np.array([11,12,13,14,15])
     
    model = Sequential()
    model.add(Dense(10, input_dim=1, activation='relu'))
    model.add(Dense(8))
    model.add(Dense(7))
    model.add(Dense(6))
    model.add(Dense(1))
     
    model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])
    model.fit(x, y, epochs=100, batch_size=1)
     
    mse = model.evaluate(x, y, batch_size=1)
    print('mse : ', mse)
     
    y_predict = model.predict(x2)
    print(y_predict)
    cs

     

     

    위 코드의 모델을 그림으로 표현해 보면 다음과 같습니다.

     

    각 노드마다 간선이 input -> ouput 방향으로 연결되어 있다고 생각해주세요!

     

     

    자세한 내용은 저번 포스팅을 참고해주세요.

    2019/12/11 - [SW개발/Python Keras] - [케라스] 무작정 튜토리얼1 - Sequential Model 구현

     

    [케라스] 무작정 튜토리얼1 - Sequential Model 구현

    딥러닝의 회귀,, 선형,, 비선형,,, 이런 이론들을 일단 접어두고 튜토리얼을 무작정 구현하면서 케라스로 딥러닝 모델을 구현하는 방법에 대해 살짝 알아봅시다. 개발 환경 : 아나콘다 가상환경에 2.0.0버전의 텐..

    ebbnflow.tistory.com

     

     

     

    저번시간 모델에는 히든레이어2개에 각 레이어당 노드를 5, 3개를 만들었고

    이번 모델은 히든레이어 4개에 각 노드를 10개, 8개, 7개, 6개를 만든 것입니다.

     

    위 두 모델은 어떤 차이가 있을까요?

    이 차이를 알아보려면 우리는 '하이퍼파라미터 튜닝'이라는 개념을 알아야 합니다.

     

     

     

     

     

    • 하이퍼파라미터 튜닝(Hyperparameter tuning)

    심층신경망 모델의 대표적인 하이퍼파라미터는 학습률(Learning rate), 히든레이어의 크기, 히든레이어의 개수 등이 있습니다. 위와 같은 하이퍼파라미터들을 조정하여 최적의 Weight를 구해 최소의 loss를 우리는 구해야 합니다.

     

    이들 외에도 세부튜닝 방법등이 있지만 튜토리얼 단계이므로 우리는 히든레이어의 개수와 크기를 조정하면 loss가 어떻게 변화하는지에 대해서 이번 튜토리얼에서 살펴볼 것입니다.

     

    • loss의 변화

    위의 모델 두개를 돌려보았을 때,

    이전의 모델의 loss(mse)값은 0.0758705266751349

    이번의 모델의 loss(mse)값은 0.005354623157836613

    값이 나왔습니다! 앞에서 말했듯이 loss값이 작은 모델을 뽑아내는 것이 좋은 성능의 모델을 만드는 작업이라고 하였습니다. 따라서 이번 모델의 loss값만 살펴보았을때는 더 많은 히든레이어의 크기와 갯수를 가진 모델이 성능이 더 좋다고 할 수 있겠습니다. 하지만 이러한 측정값은 정확도는 1에 가까우면 대략 좋고 손실은 0에 가까우면 대략 좋다는 뜻이고 정확한 것은 아닙니다.

     

     

    레이어의 수와 크기를 무작정 많이 하면 성능이 좋을까?

     

    답은 NO입니다. 어느 수준 이상의 모델이 구성되면 모델에 곱하고 더하는 연산이 많아져 오히려 성능이 저하됩니다.

     

     

    예제 코드

    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
    model = Sequential()
    model.add(Dense(1000, input_shape=(1, ), activation='relu'))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(900))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(1000))
    model.add(Dense(5))
    model.add(Dense(1))
    cs

    이렇게 너무 많은 레이어와 노드를 구성하면 오히려 성능이 떨어져서 이 결과 R2의 값은 0.5이하로 떨어졌습니다.

     

     

     

    x2 = np.array([11,12,13,14,15])
    y_predict = model.predict(x2)
    print(y_predict)

     

    이전 모델과 또 다른 부분은 x2라는 데이터를 하나 더 추가하여 predict하는 과정을 추가했다는 점입니다. 입력데이터x와 출력데이터y와 전혀다른 새로운 데이터x2를 입력하였을때 x,y를 훈련시켜 구해낸 학습을 통해 x2를 입력하였을때 출력값(y_predict)을 추론해내는 것입니다.

     

     

     

    keras io에 나와있는 predict 함수 설명

    predict

    predict(x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False)

    Generates output predictions for the input samples.

    Computation is done in batches.

    입력 샘플에 대한 출력 예측을 생성합니다.

    계산은 일괄 적으로 수행됩니다.

     

    Arguments

    • x: Input data. It could be:
      • A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs).
      • Numpy 배열(또는 배열과 유사한 것), 또는 배열 목록(모델에 여러 입력이 있는 경우)
      • A dict mapping input names to the corresponding array/tensors, if the model has named inputs.
      • 모델에 이름이 지정된 입력이 있는 경우, 입력 이름을 해당 배열/텐서에 매핑하는 dict
      • A generator or keras.utils.Sequence returning (inputs, targets) or (inputs, targets, sample weights).
      • None (default) if feeding from framework-native tensors (e.g. TensorFlow data tensors).
      • 프레임워크 네이티브 텐서에서 공급이 디폴트
    • batch_size: Integer or None. Number of samples per gradient update. If unspecified, batch_size will default to 32. Do not specify the batch_size is your data is in the form of symbolic tensors, generators, or keras.utils.Sequence instances (since they generate batches).
    • 정수 또는 None. 그라디언트 업데이트 당 샘플 수입니다. 지정되지 않은 경우 batch_size기본값은 32입니다. batch_size데이터가 기호 텐서, 생성기 또는 keras.utils.Sequence인스턴스 (일괄 처리를 생성하기 때문에) 형식임을 지정하지 마십시오 .
    • verbose: Verbosity mode, 0 or 1.
    • steps: Total number of steps (batches of samples) before declaring the prediction round finished. Ignored with the default value of None.
    • callbacks: List of keras.callbacks.Callback instances. List of callbacks to apply during prediction. See callbacks.
    • max_queue_size: Integer. Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue. If unspecified, max_queue_size will default to 10.
    • workers: Integer. Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
    • 정수. 제너레이터 또는 keras.utils.Sequence입력에만 사용 됩니다. 프로세스 기반 스레딩을 사용할 때 가동되는 최대 프로세스 수입니다. 지정되지 않은 경우 workers기본값은 1입니다. 0이면 기본 스레드에서 생성기를 실행합니다.
    • use_multiprocessing: Boolean. Used for generator or keras.utils.Sequence input only. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes.
    • 부울. 제너레이터 또는 keras.utils.Sequence입력에만 사용 됩니다. 인 경우 True프로세스 기반 스레딩을 사용하십시오. 지정되지 않은 경우 use_multiprocessing기본값은 False입니다. 이 구현은 멀티 프로세싱에 의존하기 때문에 피클 링 할 수없는 인수는 자식 프로세스로 쉽게 전달할 수 없으므로 생성기에 전달하면 안됩니다.

    Returns

    Numpy array(s) of predictions.

    Raises

    • ValueError: In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.
    • 제공된 입력 데이터와 모델의 기대치가 일치하지 않거나 상태 저장 모델이 배치 크기의 배수가 아닌 많은 샘플을 수신하는 경우.

     

     

    댓글

Designed by Tistory.