class MyCustomMetric(tf.keras.metrics.Metrics):
def __init__(self, **kwargs):
# Initialise as normal and add flag variable for when to run computation
super(MyCustomMetric, self).__init__(**kwargs)
self.metric_variable = self.add_weight(name='metric_varaible', initializer='zeros')
self.on = tf.Variable(False)
def update_state(self, y_true, y_pred, sample_weight=None):
# Use conditional to determine if computation is done
if self.on:
# run computation
self.metric_variable.assign_add(computation_result)
def result(self):
return self.metric_variable
def reset_states(self):
self.metric_variable.assign(0.)
class ToggleMetrics(tf.keras.callbacks.Callback):
'''On test begin (i.e. when evaluate() is called or
validation data is run during fit()) toggle metric flag '''
def on_test_begin(self, logs):
for metric in self.model.metrics:
if 'MyCustomMetric' in metric.name:
metric.on.assign(True)
def on_test_end(self, logs):
for metric in self.model.metrics:
if 'MyCustomMetric' in metric.name:
metric.on.assign(False)
1条答案
按热度按时间aydmsdu91#
要做到这一点,您可以在度量计算中创建一个tf.variable,它确定计算是否继续,然后在测试运行时使用回调更新它。