복붙노트

[PYTHON] Keras : 모델을 저장하고 교육을 계속하는 방법은 무엇입니까?

PYTHON

Keras : 모델을 저장하고 교육을 계속하는 방법은 무엇입니까?

나는 40 개 시대에 대해 훈련 한 모델을 가지고있다. 나는 각 신기원마다 체크 포인트를 유지하고 model.save ()로 모델을 저장했다. 교육 코드는 다음과 같습니다.

n_units = 1000
model = Sequential()
model.add(LSTM(n_units, input_shape=(None, vec_size), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(n_units, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(n_units))
model.add(Dropout(0.2))
model.add(Dense(vec_size, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adam')
# define the checkpoint
filepath="word2vec-{epoch:02d}-{loss:.4f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
# fit the model
model.fit(x, y, epochs=40, batch_size=50, callbacks=callbacks_list)

그러나 모델과 열차를 다시로드 할 때 이전에 교육을받지 않은 것처럼 시작됩니다. 마지막 훈련에서 손실이 시작되지 않습니다.

나 혼란 스러울 때, 모델 구조와 load_weight를 재정 의하여 모델을로드하면 model.predict ()가 잘 작동한다. 따라서 모델 가중치가로드됩니다.

model = Sequential()
model.add(LSTM(n_units, input_shape=(None, vec_size), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(n_units, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(n_units))
model.add(Dropout(0.2))
model.add(Dense(vec_size, activation='linear'))
filename = "word2vec-39-0.0027.hdf5"
model.load_weights(filename)
model.compile(loss='mean_squared_error', optimizer='adam')

그러나 함께 훈련을 계속할 때

filepath="word2vec-{epoch:02d}-{loss:.4f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
# fit the model
model.fit(x, y, epochs=40, batch_size=50, callbacks=callbacks_list)

손실은 초기 상태만큼 높습니다.

모델을 저장하고로드하는 몇 가지 예를 검색하여 찾았습니다. http://machinelearningmastery.com/save-load-keras-deep-learning-models/ https://github.com/fchollet/keras/issues/1872

그러나 그들 중 누구도 일하지 않습니다. 누구든지 나를 도울 수 있습니까? 감사.

최신 정보

훈련 된 Keras 모델로드 및 교육 계속

나는 노력했다.

model.save('partly_trained.h5')
del model
load_model('partly_trained.h5')

그것은 작동합니다. 하지만 파이썬 닫을 때 다시 열고 load_model. 그것은 실패합니다. 손실은 초기 상태만큼 높습니다.

최신 정보

나는 Yu-Yang의 예제 코드를 시도했다. 그것은 작동합니다. 하지만 제 코드로 돌아가서, 저는 여전히 실패했습니다. 이것이 원래의 훈련입니다. 두 번째 신기원은 손실 = 3.1 ***로 시작해야합니다.

13700/13846 [============================>.] - ETA: 0s - loss: 3.0519
13750/13846 [============================>.] - ETA: 0s - loss: 3.0511
13800/13846 [============================>.] - ETA: 0s - loss: 3.0512Epoch 00000: loss improved from inf to 3.05101, saving model to LPT-00-3.0510.h5

13846/13846 [==============================] - 81s - loss: 3.0510    
Epoch 2/60

   50/13846 [..............................] - ETA: 80s - loss: 3.1754
  100/13846 [..............................] - ETA: 78s - loss: 3.1174
  150/13846 [..............................] - ETA: 78s - loss: 3.0745

나는 파이썬을 닫고 다시 열었다. model = load_model ( "LPT-00-3.0510.h5")으로 모델을로드 한 다음

filepath="LPT-{epoch:02d}-{loss:.4f}.h5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
# fit the model
model.fit(x, y, epochs=60, batch_size=50, callbacks=callbacks_list)

손실은 4.54부터 시작됩니다.

Epoch 1/60
   50/13846 [..............................] - ETA: 162s - loss: 4.5451
   100/13846 [..............................] - ETA: 113s - loss: 4.3835

해결법

  1. ==============================

    1.문제가 어디에서 발생했는지 명확히하기가 어렵 기 때문에 코드에서 장난감 예제를 만들었고 제대로 작동하는 것 같습니다.

    문제가 어디에서 발생했는지 명확히하기가 어렵 기 때문에 코드에서 장난감 예제를 만들었고 제대로 작동하는 것 같습니다.

    import numpy as np
    from numpy.testing import assert_allclose
    from keras.models import Sequential, load_model
    from keras.layers import LSTM, Dropout, Dense
    from keras.callbacks import ModelCheckpoint
    
    vec_size = 100
    n_units = 10
    
    x_train = np.random.rand(500, 10, vec_size)
    y_train = np.random.rand(500, vec_size)
    
    model = Sequential()
    model.add(LSTM(n_units, input_shape=(None, vec_size), return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(n_units, return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(n_units))
    model.add(Dropout(0.2))
    model.add(Dense(vec_size, activation='linear'))
    model.compile(loss='mean_squared_error', optimizer='adam')
    
    # define the checkpoint
    filepath = "model.h5"
    checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
    callbacks_list = [checkpoint]
    
    # fit the model
    model.fit(x_train, y_train, epochs=5, batch_size=50, callbacks=callbacks_list)
    
    # load the model
    new_model = load_model("model.h5")
    assert_allclose(model.predict(x_train),
                    new_model.predict(x_train),
                    1e-5)
    
    # fit the model
    checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
    callbacks_list = [checkpoint]
    new_model.fit(x_train, y_train, epochs=5, batch_size=50, callbacks=callbacks_list)
    

    모델 로딩 후 손실은 계속 감소합니다. (파이썬을 재시작해도 문제가되지 않습니다)

    Using TensorFlow backend.
    Epoch 1/5
    500/500 [==============================] - 2s - loss: 0.3216     Epoch 00000: loss improved from inf to 0.32163, saving model to model.h5
    Epoch 2/5
    500/500 [==============================] - 0s - loss: 0.2923     Epoch 00001: loss improved from 0.32163 to 0.29234, saving model to model.h5
    Epoch 3/5
    500/500 [==============================] - 0s - loss: 0.2542     Epoch 00002: loss improved from 0.29234 to 0.25415, saving model to model.h5
    Epoch 4/5
    500/500 [==============================] - 0s - loss: 0.2086     Epoch 00003: loss improved from 0.25415 to 0.20860, saving model to model.h5
    Epoch 5/5
    500/500 [==============================] - 0s - loss: 0.1725     Epoch 00004: loss improved from 0.20860 to 0.17249, saving model to model.h5
    
    Epoch 1/5
    500/500 [==============================] - 0s - loss: 0.1454     Epoch 00000: loss improved from inf to 0.14543, saving model to model.h5
    Epoch 2/5
    500/500 [==============================] - 0s - loss: 0.1289     Epoch 00001: loss improved from 0.14543 to 0.12892, saving model to model.h5
    Epoch 3/5
    500/500 [==============================] - 0s - loss: 0.1169     Epoch 00002: loss improved from 0.12892 to 0.11694, saving model to model.h5
    Epoch 4/5
    500/500 [==============================] - 0s - loss: 0.1097     Epoch 00003: loss improved from 0.11694 to 0.10971, saving model to model.h5
    Epoch 5/5
    500/500 [==============================] - 0s - loss: 0.1057     Epoch 00004: loss improved from 0.10971 to 0.10570, saving model to model.h5
    

    BTW는 save_weight () 및 load_weight ()가 옵티마이 저를 저장 /로드하지 않기 때문에 모델을 다시 정의한 다음 load_weight ()를 확실히 재정의 할 수 없습니다.

  2. ==============================

    2.내 코드를이 예제와 비교했다. http://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/ 조심스럽게 라인 단위로 차단하고 다시 실행하십시오. 하루 종일, 마침내, 나는 틀린 것을 발견했다.

    내 코드를이 예제와 비교했다. http://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/ 조심스럽게 라인 단위로 차단하고 다시 실행하십시오. 하루 종일, 마침내, 나는 틀린 것을 발견했다.

    char-int 매핑을 만들 때, 나는

    # title_str_reduced is a string
    chars = list(set(title_str_reduced))
    # make char to int index mapping
    char2int = {}
    for i in range(len(chars)):
        char2int[chars[i]] = i    
    

    집합은 정렬되지 않은 데이터 구조입니다. 파이썬에서, 세트가 정렬 된리스트로 변환 될 때, 그 순서는 랜덤하게 주어집니다. 따라서 파이썬을 다시 열 때마다 char2int 사전은 무작위로 추출됩니다. 정렬 된 () 코드를 추가하여 코드를 수정했습니다.

    chars = sorted(list(set(title_str_reduced)))
    

    이렇게하면 고정 된 순서로 변환됩니다.

  3. ==============================

    3.모델을 저장하는 공식 kera 문서는 다음과 같습니다.

    모델을 저장하는 공식 kera 문서는 다음과 같습니다.

    https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model

    이 게시물에서 저자는 모델을 파일로 저장하고로드하는 두 가지 예를 제공합니다.

  4. from https://stackoverflow.com/questions/45393429/keras-how-to-save-model-and-continue-training by cc-by-sa and MIT license