在实践中,“提前停止”主要通过以下方式完成:(1) 训练 X 个 epoch,(2)每次达到新的最佳性能时保存模型,(3) 选择最佳模型。“最佳性能”定义为实现最高(例如准确性)或最低(例如损失)验证指标 - 下面的示例脚本:best_val_loss = 999 # arbitrary init - should be high if 'best' is low, and vice versanum_epochs = 5epoch = 0while epoch < num_epochs: model.train_on_batch(x_train, y_train) # get x, y somewhere in the loop val_loss = model.evaluate(x_val, y_val) if val_loss < best_val_loss: model.save(best_model_path) # OR model.save_weights() print("Best model w/ val loss {} saved to {}".format(val_loss, best_model_path)) # ... epoch += 1请参阅保存 Keras 模型。如果你宁愿直接提前停止,那么定义一些指标 - 即条件 - 这将结束火车循环。例如,while True: loss = model.train_on_batch(...) if loss < .02: break