如何防止 Keras 在训练期间计算指标
How to prevent Keras from computing metrics during training
我正在使用 Tensorflow/Keras 2.4.1 并且我有一个(无监督的)自定义指标,它将我的几个模型输入作为参数,例如:
model = build_model() # returns a tf.keras.Model object
my_metric = custom_metric(model.output, model.input[0], model.input[1])
model.add_metric(my_metric)
[...]
model.fit([...]) # training with fit
但是,碰巧 custom_metric
非常昂贵,所以我希望它仅在验证期间计算。我发现了这个 ,但我几乎不明白如何使解决方案适应使用多个模型输入作为参数的指标,因为 update_state
方法似乎不灵活。
在我的上下文中,除了编写我自己的训练循环之外,有没有办法避免在训练期间计算我的指标?
此外,令我感到非常惊讶的是,我们无法直接向 Tensorflow 指定某些指标仅应在验证时计算,是否有原因?
此外,由于训练模型是为了优化损失,并且训练数据集不应该用于评估模型,我什至不明白为什么默认情况下 Tensorflow 在训练期间计算指标。
我能够使用 learning_phase
但只能在符号张量模式(图形)模式下使用:
所以,首先我们需要禁用eager模式(这必须在导入tensorflow之后立即完成):
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
然后您可以使用符号 if (backend.switch
):
创建您的指标
def metric_graph(in1, in2, out):
actual_metric = out * (in1 + in2)
return K.switch(K.learning_phase(), tf.zeros((1,)), actual_metric)
方法add_metric
会询问名称和聚合方法,您可以设置为"mean"
。
所以,这是一个例子:
x1 = numpy.ones((5,3))
x2 = numpy.ones((5,3))
y = 3*numpy.ones((5,1))
vx1 = numpy.ones((5,3))
vx2 = numpy.ones((5,3))
vy = 3*numpy.ones((5,1))
def metric_eager(in1, in2, out):
if (K.learning_phase()):
return 0
else:
return out * (in1 + in2)
def metric_graph(in1, in2, out):
actual_metric = out * (in1 + in2)
return K.switch(K.learning_phase(), tf.zeros((1,)), actual_metric)
ins1 = Input((3,))
ins2 = Input((3,))
outs = Concatenate()([ins1, ins2])
outs = Dense(1)(outs)
model = Model([ins1, ins2],outs)
model.add_metric(metric_graph(ins1, ins2, outs), name='my_metric', aggregation='mean')
model.compile(loss='mse', optimizer='adam')
model.fit([x1, x2],y, validation_data=([vx1, vx2], vy), epochs=3)
我认为仅在验证时计算指标的最简单解决方案是使用自定义回调。
这里我们定义我们的虚拟回调:
class MyCustomMetricCallback(tf.keras.callbacks.Callback):
def __init__(self, train=None, validation=None):
super(MyCustomMetricCallback, self).__init__()
self.train = train
self.validation = validation
def on_epoch_end(self, epoch, logs={}):
mse = tf.keras.losses.mean_squared_error
if self.train:
logs['my_metric_train'] = float('inf')
X_train, y_train = self.train[0], self.train[1]
y_pred = self.model.predict(X_train)
score = mse(y_train, y_pred)
logs['my_metric_train'] = np.round(score, 5)
if self.validation:
logs['my_metric_val'] = float('inf')
X_valid, y_valid = self.validation[0], self.validation[1]
y_pred = self.model.predict(X_valid)
val_score = mse(y_pred, y_valid)
logs['my_metric_val'] = np.round(val_score, 5)
给定这个虚拟模型:
def build_model():
inp1 = Input((5,))
inp2 = Input((5,))
out = Concatenate()([inp1, inp2])
out = Dense(1)(out)
model = Model([inp1, inp2], out)
model.compile(loss='mse', optimizer='adam')
return model
和此数据:
X_train1 = np.random.uniform(0,1, (100,5))
X_train2 = np.random.uniform(0,1, (100,5))
y_train = np.random.uniform(0,1, (100,1))
X_val1 = np.random.uniform(0,1, (100,5))
X_val2 = np.random.uniform(0,1, (100,5))
y_val = np.random.uniform(0,1, (100,1))
您可以使用自定义回调来计算训练和验证的指标:
model = build_model()
model.fit([X_train1, X_train2], y_train, epochs=10,
callbacks=[MyCustomMetricCallback(train=([X_train1, X_train2],y_train), validation=([X_val1, X_val2],y_val))])
仅在验证时:
model = build_model()
model.fit([X_train1, X_train2], y_train, epochs=10,
callbacks=[MyCustomMetricCallback(validation=([X_val1, X_val2],y_val))])
仅在火车上:
model = build_model()
model.fit([X_train1, X_train2], y_train, epochs=10,
callbacks=[MyCustomMetricCallback(train=([X_train1, X_train2],y_train))])
只记得回调评估数据的指标one-shot,就像keras在[=16=上默认计算的任何metric/loss ].
here 是 运行 代码。
我正在使用 Tensorflow/Keras 2.4.1 并且我有一个(无监督的)自定义指标,它将我的几个模型输入作为参数,例如:
model = build_model() # returns a tf.keras.Model object
my_metric = custom_metric(model.output, model.input[0], model.input[1])
model.add_metric(my_metric)
[...]
model.fit([...]) # training with fit
但是,碰巧 custom_metric
非常昂贵,所以我希望它仅在验证期间计算。我发现了这个 update_state
方法似乎不灵活。
在我的上下文中,除了编写我自己的训练循环之外,有没有办法避免在训练期间计算我的指标? 此外,令我感到非常惊讶的是,我们无法直接向 Tensorflow 指定某些指标仅应在验证时计算,是否有原因?
此外,由于训练模型是为了优化损失,并且训练数据集不应该用于评估模型,我什至不明白为什么默认情况下 Tensorflow 在训练期间计算指标。
我能够使用 learning_phase
但只能在符号张量模式(图形)模式下使用:
所以,首先我们需要禁用eager模式(这必须在导入tensorflow之后立即完成):
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
然后您可以使用符号 if (backend.switch
):
def metric_graph(in1, in2, out):
actual_metric = out * (in1 + in2)
return K.switch(K.learning_phase(), tf.zeros((1,)), actual_metric)
方法add_metric
会询问名称和聚合方法,您可以设置为"mean"
。
所以,这是一个例子:
x1 = numpy.ones((5,3))
x2 = numpy.ones((5,3))
y = 3*numpy.ones((5,1))
vx1 = numpy.ones((5,3))
vx2 = numpy.ones((5,3))
vy = 3*numpy.ones((5,1))
def metric_eager(in1, in2, out):
if (K.learning_phase()):
return 0
else:
return out * (in1 + in2)
def metric_graph(in1, in2, out):
actual_metric = out * (in1 + in2)
return K.switch(K.learning_phase(), tf.zeros((1,)), actual_metric)
ins1 = Input((3,))
ins2 = Input((3,))
outs = Concatenate()([ins1, ins2])
outs = Dense(1)(outs)
model = Model([ins1, ins2],outs)
model.add_metric(metric_graph(ins1, ins2, outs), name='my_metric', aggregation='mean')
model.compile(loss='mse', optimizer='adam')
model.fit([x1, x2],y, validation_data=([vx1, vx2], vy), epochs=3)
我认为仅在验证时计算指标的最简单解决方案是使用自定义回调。
这里我们定义我们的虚拟回调:
class MyCustomMetricCallback(tf.keras.callbacks.Callback):
def __init__(self, train=None, validation=None):
super(MyCustomMetricCallback, self).__init__()
self.train = train
self.validation = validation
def on_epoch_end(self, epoch, logs={}):
mse = tf.keras.losses.mean_squared_error
if self.train:
logs['my_metric_train'] = float('inf')
X_train, y_train = self.train[0], self.train[1]
y_pred = self.model.predict(X_train)
score = mse(y_train, y_pred)
logs['my_metric_train'] = np.round(score, 5)
if self.validation:
logs['my_metric_val'] = float('inf')
X_valid, y_valid = self.validation[0], self.validation[1]
y_pred = self.model.predict(X_valid)
val_score = mse(y_pred, y_valid)
logs['my_metric_val'] = np.round(val_score, 5)
给定这个虚拟模型:
def build_model():
inp1 = Input((5,))
inp2 = Input((5,))
out = Concatenate()([inp1, inp2])
out = Dense(1)(out)
model = Model([inp1, inp2], out)
model.compile(loss='mse', optimizer='adam')
return model
和此数据:
X_train1 = np.random.uniform(0,1, (100,5))
X_train2 = np.random.uniform(0,1, (100,5))
y_train = np.random.uniform(0,1, (100,1))
X_val1 = np.random.uniform(0,1, (100,5))
X_val2 = np.random.uniform(0,1, (100,5))
y_val = np.random.uniform(0,1, (100,1))
您可以使用自定义回调来计算训练和验证的指标:
model = build_model()
model.fit([X_train1, X_train2], y_train, epochs=10,
callbacks=[MyCustomMetricCallback(train=([X_train1, X_train2],y_train), validation=([X_val1, X_val2],y_val))])
仅在验证时:
model = build_model()
model.fit([X_train1, X_train2], y_train, epochs=10,
callbacks=[MyCustomMetricCallback(validation=([X_val1, X_val2],y_val))])
仅在火车上:
model = build_model()
model.fit([X_train1, X_train2], y_train, epochs=10,
callbacks=[MyCustomMetricCallback(train=([X_train1, X_train2],y_train))])
只记得回调评估数据的指标one-shot,就像keras在[=16=上默认计算的任何metric/loss ].
here 是 运行 代码。