从Keras检查站装货

2024-09-30 18:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Keras培训一个模型,在那里我使用以下代码保存了所有内容

filepath = "project_model.hdh5"

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

然后我使用以下代码来运行培训

for _ in range(20):
    for j in range(len(mfcc_data_padded_transposed[j])):
        batch_input=[mfcc_data_padded_transposed[j]]
        batch_input = np.array(batch_input)
        batch_input = batch_input/np.max(batch_input)
        batch_output = [y_labels_mfcc[j]]
        batch_output = np.array(batch_output)
        input_lengths2 = input_lengths_mfcc[j]
        label_lengths2 = label_lengths_mfcc[j]
        input_lengths2 = np.array(input_lengths2)
        label_lengths2 = np.array(label_lengths2)
        inputs = {'the_input': batch_input,
         'the_labels': batch_output,
         'input_length': input_lengths2,
         'label_length': label_lengths2}
        outputs = {'ctc': np.zeros([1])} 
        model.fit(inputs, outputs, epochs=1, verbose =1, callbacks=[checkpoint])

我做上述操作是为了试验检查点,因为我不确定我是否正确使用了它

现在,这个培训是以.001的学习率完成的。现在,在运行了一段时间的训练循环之后,如果我决定将学习速率更改为.002,我是否必须运行与模型相关的所有代码(模型结构,然后是优化,等等)?如果我这样做了,我如何从停止训练时的前一个状态加载?另一个问题是,如果我重新启动电脑,并使用我之前在这里共享的检查点代码运行jupyter计算单元,这会替换以前保存的文件吗?加载保存的文件和重量并从那里恢复训练的理想方法是什么?我问这个问题的原因是,当我遵循Keras文档时,它似乎只是从一开始就开始了


Tags: 代码模型projectinputoutputverbosemodelnp
1条回答
网友
1楼 · 发布于 2024-09-30 18:24:22

Now after running the training loop for a while if I decide to change the learning rate to say .002, would I have to run all the codes that are related to the models (the model structure, then the optimization, etc)?

您可以在培训期间或加载模型后更新学习率

记住,学习率不属于模型体系结构,它属于优化器(在模型编译期间分配)。学习率是一个超参数,在梯度下降过程中调节权重更新的幅度(如下所示α):

enter image description here

因此,在初始培训之后,您可以加载(保存的)模型,以新的学习速率更新优化器(可能还可以为编译器分配自定义对象),然后继续培训。请记住,在长时间训练模型后更改优化器本身可能会产生较差的精度结果,因为您的模型现在必须根据新优化器的权重计算重新校准

how do I load from the previous state from when I stopped the training?

在Keras中,您可以选择保存/加载整个模型(包括体系结构、权重、优化器状态;或者只保存权重;或者只保存体系结构(source)

要保存/加载整个模型,请执行以下操作:

from keras.models import load_model

model.save('my_model.h5')
model = load_model('my_model.h5')

要仅保存/加载模型权重

model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5')

也可以在模型加载期间指定自定义对象:

model = load_model(filepath, custom_objects={'loss': custom_loss})

Other question is, if I restart the PC, and run the jupyter cell with checkpoint codes that I shared here earlier, would that replace the previously saved file?

取决于检查点中使用的文件路径:“如果文件路径为weights.{epoch:02d}-{val_loss:.2f}.hdf5,则模型检查点将与文件名中的历元号和验证丢失一起保存”。因此,如果您对文件路径使用唯一格式,则可以避免覆盖以前保存的模型。source

What is an ideal way to load the saved files and weights and resume training from there?

例如:

# Define model
model = keras.models.Sequential()

model.add(L.InputLayer([None],dtype='int32'))
model.add(L.Embedding(len(all_words),50))
model.add(keras.layers.Bidirectional(L.SimpleRNN(5,return_sequences=True)))

# Define softmax layer for every time step (hence TimeDistributed layer)
stepwise_dense = L.Dense(len(all_words),activation='softmax')
stepwise_dense = L.TimeDistributed(stepwise_dense)
model.add(stepwise_dense)

import keras.backend as K

# compile model with adam optimizer
model.compile('adam','categorical_crossentropy')

# print learning rate
print(f"Model learning rate is: {K.get_value(model.optimizer.lr):.3f}")

# train model
model.fit_generator(generate_batches(train_data), len(train_data)/BATCH_SIZE,
                    callbacks=[EvaluateAccuracy()], epochs=1)

# save model (weights, architecture, optimizer state)
model.save('my_model.h5')

# delete existing model
del model

结果

Model learning rate is: 0.001
Epoch 1/1
1341/1343 [============================>.] - ETA: 0s - loss: 0.4288
Measuring validation accuracy...
Validation accuracy: 0.93138
from keras.models import load_model

# create new adam optimizer with le-04 learning rate (previous: 1e-03)
adam = keras.optimizers.Adam(lr=1e-4)

# load model
model = load_model('my_model.h5', compile=False)

# compile model and print new learning rate
model.compile(adam, 'categorical_crossentropy')
print(f"Model learning rate is: {K.get_value(model.optimizer.lr):.4f}")

# train model for 3 more epochs with new learning rate
print("Training model: ")
model.fit_generator(generate_batches(train_data),len(train_data)/BATCH_SIZE,
                    callbacks=[EvaluateAccuracy()], epochs=3,)

结果

Model learning rate is: 0.0001
Training model: 
Epoch 1/3
1342/1343 [============================>.] - ETA: 0s - loss: 0.0885
Measuring validation accuracy...
Validation accuracy: 0.93568

1344/1343 [==============================] - 41s - loss: 0.0885    
Epoch 2/3

1342/1343 [============================>.] - ETA: 0s - loss: 0.0768
Measuring validation accuracy...
Validation accuracy: 0.93925

1344/1343 [==============================] - 39s - loss: 0.0768    
Epoch 3/3
1343/1343 [============================>.] - ETA: 0s - loss: 0.0701
Measuring validation accuracy...
Validation accuracy: 0.94180

有关具体案例的更多信息,请访问Keras FAQ

相关问题 更多 >