深さ学習オーバーフィット


学習内容
ANNモデリングコメント
Q 1)バイナリ分類問題において出力ノードが1つの場合

  • Dense(2)->疎分類クロスエントロピーは,複数のクラス計算損失を受けるため,出力dimが2より大きくなければならない.

  • Dese(1)->binary crossentropy、0.5以上は1、0未満は0です.
  • Q 2)固定ランダムシード
    np.random.seed(3)
    tf.random.set_seed(3)
    Overfitting
    タイプ:
    1. Early stopping
    2. weight decay(L1, L2)
    3. Constraint
    4. Dropout
    Early stopping
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense
    import tensorflow.keras.layers as Layer
    
    import numpy as np
    import pandas as pd
    import tensorflow as tf
    import keras, os
    
    # 모델 학습을 위한 코드
    
    # 변수 설정을 따로 하는 방법을 적용하기 위한 코드
    batch_size = 30
    epochs_max = 1
    
    # 학습시킨 데이터를 저장시키기 위한 코드
    checkpoint_filepath = "FMbest.hdf5"
    
    # overfitting을 방지하기 위해서 학습 중 early stop을 수행
    early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)
    #min_delta : 모델이 향상됐다고 판단하는 최소 기준
    #patience : patience epoch동안 모델향상이 없다면 stop,
    
    
    # Validation Set을 기준으로 가장 최적의 모델을 찾기 위한 코드
    save_best = tf.keras.callbacks.ModelCheckpoint(
        filepath=checkpoint_filepath, monitor='val_loss', verbose=1, save_best_only=True,
        save_weights_only=True, mode='auto', save_freq='epoch', options=None)
        #save_best_only : epoch당 학습된 모델 중 가장 성능이 좋은 모델만 저장?
        #mode : monitor에 따라 min값으로 모델을 판단 or max값으로 모델을 판단
    
    # 모델 학습 코드 + early stop + Best model
    model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs_max, verbose=1, 
              validation_data=(X_test,y_test), 
              callbacks=[early_stop, save_best])
              
    # 체크포인트에 저장된 가중치들을 불러들이는 코드
    model.load_weights(checkpoint_filepath)
    
    # best model을 이용한 테스트 데이터 예측 정확도 재확인 코드
    model.predict(X_test[0:1])
    test_loss, test_acc = model.evaluate(X_test,  y_test, verbose=2)
    weight decay, constraint
    # 모델 구성을 확인
    model = Sequential([
        Flatten(input_shape=(28, 28)),
        Dense(64, input_dim=64,
                kernel_regularizer=regularizers.l2(0.01),    # 가중치 정규화방법
                activity_regularizer=regularizers.l1(0.01)), # 출력값 정규화방법
                #가중치 정규화에는 L2를, 출력값에는 L1을 넣던데 노드는 살려두고 노드에서 출력되는 값 중 불필요한 값을 L1으로 처리하기 위함으로 생각된다.
                
                kernel_constraint=MaxNorm(2.)) #가중치들의 norm값이 최대 2로 제한시키는 것을 의미
                
        Dense(10, activation='softmax')
        Layer.Dropout(0.5) 바로 위 노드의 50%를 drop시킴
    ])
    Dropout
    Layers.Dropout(0.1) #이 코드 위 layer의 노드를 10% drop
    Learning rate
    #learning rate변화시키기, 갈수록 감소
    
    lr_schedule = keras.optimizers.schedules.ExponentialDecay(
        initial_learning_rate=1e-2,
        decay_steps=10000,
        decay_rate=0.9)
    
    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule) #toptimizer에 learning rate 추가가능
                 , loss='sparse_categorical_crossentropy'
                 , metrics=['accuracy'])