我正在安装一个train_生成器,通过自定义回调,我想在我的validation_生成器上计算自定义度量。
如何在自定义回调中访问参数validation_steps
和validation_data
?
它不在self.params
中,也不在self.model
中。这是我想做的。任何不同的方法都会受到欢迎。
model.fit_generator(generator=train_generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_steps,
callbacks=[CustomMetrics()])
class CustomMetrics(keras.callbacks.Callback):
def on_epoch_end(self, batch, logs={}):
for i in validation_steps:
# features, labels = next(validation_data)
# compute custom metric: f(features, labels)
return
路缘石:2.1.1
更新
我设法将验证数据传递给自定义回调的构造函数。然而,这会导致一个恼人的“内核似乎已经死了”。它将自动重新启动。我怀疑这样做是否正确。有什么建议吗?
class CustomMetrics(keras.callbacks.Callback):
def __init__(self, validation_generator, validation_steps):
self.validation_generator = validation_generator
self.validation_steps = validation_steps
def on_epoch_end(self, batch, logs={}):
self.scores = {
'recall_score': [],
'precision_score': [],
'f1_score': []
}
for batch_index in range(self.validation_steps):
features, y_true = next(self.validation_generator)
y_pred = np.asarray(self.model.predict(features))
y_pred = y_pred.round().astype(int)
self.scores['recall_score'].append(recall_score(y_true[:,0], y_pred[:,0]))
self.scores['precision_score'].append(precision_score(y_true[:,0], y_pred[:,0]))
self.scores['f1_score'].append(f1_score(y_true[:,0], y_pred[:,0]))
return
metrics = CustomMetrics(validation_generator, validation_steps)
model.fit_generator(generator=train_generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_steps,
shuffle=True,
callbacks=[metrics],
verbose=1)
我锁定了相同问题的解决方案,然后在接受的答案here中找到了您的解决方案和另一个解决方案。如果第二个解决方案有效,我认为它将比在“划时代结束时”再次遍历所有验证更好
其思想是将目标和pred占位符保存在变量中,并通过“批处理结束时”的自定义回调更新变量
以下是方法:
Reference
路缘石2.2.4
您可以直接在self.validation_数据上迭代,以在每个epoch结束时聚合所有验证数据。如果要计算整个验证数据集的精度、召回和F1:
然后可以向回调参数添加有效的\u度量:
一定要将它放在回调的开头,以防希望其他回调使用这些度量。
相关问题 更多 >
编程相关推荐