Python 自定义回调中的访问丢失和模型
我读过这篇文章,但我不知道如何获得所有其他参数 这是我的密码Python 自定义回调中的访问丢失和模型,python,tensorflow,keras,callback,Python,Tensorflow,Keras,Callback,我读过这篇文章,但我不知道如何获得所有其他参数 这是我的密码 (hits, ndcgs) = evaluate_model(model, testRatings, testNegatives, topK, evaluation_threads) hr, ndcg, loss = np.array(hits).mean(), np.array(ndcgs).mean(), hist.history['loss'][0] print('Iteration %d [%.1f s]: HR =
(hits, ndcgs) = evaluate_model(model, testRatings, testNegatives, topK, evaluation_threads)
hr, ndcg, loss = np.array(hits).mean(), np.array(ndcgs).mean(), hist.history['loss'][0]
print('Iteration %d [%.1f s]: HR = %.4f, NDCG = %.4f, loss = %.4f [%.1f s]'
% (epoch, t2-t1, hr, ndcg, loss, time()-t2))
if hr > best_hr:
best_hr, best_ndcg, best_iter = hr, ndcg, epoch
if args.out > 0:
model.save(model_out_file, overwrite=True)
如您所见,我需要model
、hist
和model.save
。
有没有办法在自定义回调中使用这三个参数?
这样我就可以将所有这些写入自定义回调
class CustomCallback(keras.callbacks.Callback):
def on_epoch_end(self, logs=None):
keys = list(logs.keys())
print("Stop training; got log keys: {}".format(keys))
该模型是一个,因此您可以使用self.model
直接访问它。要访问丢失值,可以使用传递给的“logs”对象,该对象将包含一个名为“loss”的键
如果需要访问其他变量(在培训期间不会更改),则可以将它们设置为回调的实例变量,并通过定义\uuuuu init\uuu
函数在回调构造期间添加它们
class CustomCallback(keras.callbacks.Callback):
def __init__(self, testRatings, testNegatives, topK, evaluation_threads):
super().__init__()
self.testRatings = testRatings
self.testNegatives = testNegatives
self.topK = topK
self.evaluation_threads = evaluation_threads
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
current_loss = logs.get("loss")
if current_loss:
print("my_loss: ", current_loss)
print("my_model", self.model)
# the attributes are accessble with self
print("my topK atributes", self.topK)
# you can then create the callback by passing the correct attributes
my_callback = CustomCallback(testRatings, testNegatives, topK, evaluation_threads)
注意:如果您想在每个历元之间评估模型,并在模型获得最佳指标时保存模型,我建议您查看:
- 在中,您可以实际提供一个测试集
- 提供将在列车和测试集上计算的度量的
- 如果提供选项
save\u best\u only
self
是模型吗?我还可以保存模型
并获取模型
?很抱歉,代码应该在一个历元的每一个末尾都这样做。您可以定义on\u epoch\u end
方法在每个历元都这样做self
是引用对象的关键字,请参见,因此在这种情况下,它引用回调对象。如果您想保存模型,可以通过属性访问模型,因此self.model.save(“/path/to/saved\u model”)
就可以了。非常感谢您的回答!是否还有向回调传递参数的选项?例如,我在这里使用testRatings、testNegatives、topK、evaluation\u threads
。这可以传递给回调吗?是的,可以在回调的\uuuu init\uuuu
函数(构造函数)中传递。它们可以作为“实例变量”访问,您可以在“谢谢,我了解到了”中了解更多信息。不幸的是,我没有理解正确。你能给我看一个代码示例吗?