简体   繁体   English

如何为每个时期保存 keras model 的权重?

[英]How to save weights of keras model for each epoch?

I want to save keras model and I want to save weights of each epoch to have best weights.我想保存 keras model 并且我想保存每个时期的权重以获得最佳权重。 How I do that?我该怎么做?

Any help would be appreciated.任何帮助,将不胜感激。

code :代码

def createModel():
    input_shape=(1, 22, 5, 3844)
    model = Sequential()
    #C1
    model.add(Conv3D(16, (22, 5, 5), strides=(1, 2, 2), padding='same',activation='relu',data_format= "channels_first", input_shape=input_shape))
    model.add(keras.layers.MaxPooling3D(pool_size=(1, 2, 2),data_format= "channels_first",  padding='same'))
    model.add(BatchNormalization())
    #C2
    model.add(Conv3D(32, (1, 3, 3), strides=(1, 1,1), padding='same',data_format= "channels_first",  activation='relu'))#incertezza se togliere padding
    model.add(keras.layers.MaxPooling3D(pool_size=(1,2, 2),data_format= "channels_first", ))
    model.add(BatchNormalization())

     #C3
    model.add(Conv3D(64, (1,3, 3), strides=(1, 1,1), padding='same',data_format= "channels_first",  activation='relu'))#incertezza se togliere padding
    model.add(keras.layers.MaxPooling3D(pool_size=(1,2, 2),data_format= "channels_first",padding='same' ))
    model.add(Dense(64, input_dim=64, kernel_regularizer=regularizers.l2(0.01), activity_regularizer=regularizers.l1(0.01)))
    model.add(BatchNormalization())

    model.add(Flatten())
    model.add(Dropout(0.5))
    model.add(Dense(256, activation='sigmoid'))
    model.add(Dropout(0.5))
    model.add(Dense(2, activation='softmax'))

    opt_adam = keras.optimizers.Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
    model.compile(loss='categorical_crossentropy', optimizer=opt_adam, metrics=['accuracy'])

    return model

model.get_weights() will return a tensor as a numpy array. model.get_weights() 将返回一个张量作为 numpy 数组。 You can save those weights in a file with extension.npy using np.save().您可以使用 np.save() 将这些权重保存在扩展名为.npy 的文件中。

To save weights every epoch, you can use something known as callbacks in Keras.要在每个 epoch 保存权重,您可以在 Keras 中使用称为回调的东西。

from keras.callbacks import ModelCheckpoint

before you do model.fit, define a checkpoint as below在你做 model.fit 之前,定义一个检查点如下

checkpoint = ModelCheckpoint(.....) , assign the argument 'period' as 1 which assigns the periodicity of epochs. checkpoint = ModelCheckpoint(.....) ,将参数 'period' 指定为 1,它指定 epoch 的周期性。 This should do it.这应该这样做。

I am not sure it will work but you can try writing callback and inside callback you can save the weights.我不确定它是否会起作用,但您可以尝试编写回调,在回调内部您可以保存权重。

Eg.例如。

checkpoint = ModelCheckpoint("best_model.hdf5", monitor='loss', verbose=1,
    save_best_only=True, mode='auto', period=1)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[checkpoint])

source = https://medium.com/@italojs/saving-your-weights-for-each-epoch-keras-callbacks-b494d9648202来源 = https://medium.com/@italojs/saving-your-weights-for-each-epoch-keras-callbacks-b494d9648202

You should use model.get_weights() and LambdaCallback function together:您应该一起使用 model.get_weights() 和 LambdaCallback function :

  1. model.get_weights() : Returns a list of all weight tensors in the model, as Numpy arrays. model.get_weights() :返回 model 中所有权重张量的列表,如 Z55F00E1DAA52B7CB5C5BC865E89DBC792Z11554E.

     model = Sequential() weights = model.get_weights()
  2. LambdaCallback : This callback is constructed with anonymous functions that will be called at the appropriate time LambdaCallback :此回调由匿名函数构造,将在适当的时间调用

    import json json_log = open('loss_log.json', mode='wt', buffering=1) json_logging_callback = LambdaCallback( on_epoch_end=lambda epoch, logs: json_log.write( json.dumps({'epoch': epoch, 'loss': logs['loss']}) + '\n'), on_train_end=lambda logs: json_log.close() ) model.fit(..., callbacks=[json_logging_callback])

When your code is considered, you should write callback function and add to your model :考虑您的代码时,您应该编写回调function 并添加到您的model

import json
from keras.callbacks import LambdaCallback

json_log = open('loss_log.json', mode='wt', buffering=1)
json_logging_callback = LambdaCallback(
            on_epoch_end=lambda epoch, logs: json_log.write(
                json.dumps({'epoch': epoch, 
                            'loss': logs['loss'],
                            'weights': model.get_weights()}) + '\n'),
            on_train_end=lambda logs: json_log.close()
)

model.compile(loss='categorical_crossentropy',
              optimizer=opt_adam, 
              metrics=['accuracy'])

model.fit_generator(..., callbacks=[json_logging_callback])

This code write your all weights in all layers to json file.此代码将所有层中的所有权重写入 json 文件。 If you want to save weights in specific layer, just change the code with如果你想在特定层保存权重,只需更改代码

model.layers[0].get_weights()

You can write a ModelCheckpoint callback using tf.keras.callbacks.ModelCheckpoint to save weights every epoch.您可以使用tf.keras.callbacks.ModelCheckpoint编写一个 ModelCheckpoint 回调来保存每个时期的权重。 If you are using recent Tensorflow like TF2.1 or later, then You need to use save_freq='epoch' to save weights every epoch instead of using period=1 as other answer mentioned.如果您使用的是最近的 Tensorflow,例如TF2.1或更高版本,那么您需要使用save_freq='epoch'来保存每个时期的权重,而不是使用period=1作为提到的其他答案。 Please check entire example here在此处查看整个示例

callback is as follows回调如下

checkpoint_path = "./training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

cp_callback = tf.keras.callbacks.ModelCheckpoint(
   checkpoint_path, verbose=1, save_weights_only=True,
   # Save weights, every epoch.
   save_freq='epoch')

calling the model training调用 model 培训

# Create a basic model instance
model=create_model()
model.save_weights(checkpoint_path.format(epoch=0))
model.fit(x_train, y_train,
         epochs = 50, callbacks = [cp_callback],
         validation_data = (x_test,y_test),
         verbose=0)

Hope this helps.希望这可以帮助。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM