자동 매개변수 조정 도구:Keras-Tuner의 기본 사용

10520 단어 기술 창고
기본 코드로 라이브러리 파일을 가져옵니다.
from tensorflow.keras.datasets import fashion_mnist
from tensorflow import keras
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Activation
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

모델 구축 함수를 정의합니다. 여기서 hp는 슈퍼 파라미터 조정 대상입니다.
from kerastuner.tuners import RandomSearch

#     ,  hp  ,              ,      
def build_model(hp):
    model = keras.Sequential()
    model.add(layers.Input(shape=(28, 28, 1)))
    model.add(layers.Flatten())
    model.add(layers.Dense(units=hp.Int('units',
                                        min_value=32,
                                        max_value=512,
                                        step=32),
                           activation='relu'))
    model.add(layers.Dense(10, activation='softmax'))
    model.compile(
        optimizer=keras.optimizers.Adam(
            hp.Choice('learning_rate',
                      values=[1e-2, 1e-3, 1e-4])),
#         loss='categorical_crossentropy',
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy'])
    return model

정의 최적화기
#       
tuner = RandomSearch(
    build_model,
    objective='val_accuracy',  #       'val_accuracy'(     )
    max_trials=5,   #    5 ,       
    executions_per_trial=3, #          
    directory='my_dir',
    project_name='helloworld')

검색 시작
tuner.search(x=x_train,
             y=y_train,
             verbose=2, # just slapping this here bc jupyter notebook. The console out was getting messy.
             epochs=1,
             batch_size=64,
             #callbacks=[tensorboard],  # if you have callbacks like tensorboard, they go here.
             validation_data=(x_test, y_test))

관련 매개변수 저장하기
tuner.results_summary()


with open(f"tuner_{int(time.time())}.pkl", "wb") as f:
    pickle.dump(tuner, f)

관련 매개 변수 다시 읽기
import pickle
tuner = pickle.load(open("tuner_1576628824.pkl","rb"))

tuner.get_best_hyperparameters()[0].values
tuner.get_best_models()[0].summary()

참조 블로그: Keras Tuner 자동 조정 도구 사용 입문 강좌 Optimizing Neural Network Structures with Keras-Tuner youtube: Optimizing Neural Network Structures with Keras-Tuner

좋은 웹페이지 즐겨찾기