我正在使用带有自定义Estimator的Tensorflow 1.10。为了测试我的训练/评估循环,我每次都将相同的图像/标签馈入网络,因此我希望网络能够快速收敛。
我也使用相同的图像进行评估,但损失值比训练时大得多。经过2000步训练后,损失为:
INFO:tensorflow:最后一步的损失: 0.01181452
但评估为:
步骤2000的评估损失: 0.41252694
这对我来说似乎是错的。看起来与this线程中的问题相同。使用evaluate
的{{1}}方法时,有什么特别需要考虑的东西吗?
我已将here之类的模型(FeatureNet)定义为Estimator
和tf.keras.Model
方法对init
的继承。
我的call
如下:
model_fn
然后在主体部分中,我将使用自定义的估算器进行训练和评估:
def model_fn(features, labels, mode):
resize_shape = (180, 320)
num_dimensions = 16
model = featurenet.FeatureNet(resize_shape, num_dimensions=num_dimensions)
training = (mode == tf.estimator.ModeKeys.TRAIN)
seg_pred = model(features, training)
predictions = {
# Generate predictions (for PREDICT mode)
"seg_pred": seg_pred
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# Calculate Loss (for both TRAIN and EVAL modes)
seg_loss = tf.reduce_mean(tf.keras.backend.binary_crossentropy(labels['seg_true'], seg_pred))
loss = seg_loss
# Configure the Training Op (for TRAIN mode)
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.MomentumOptimizer(learning_rate=1e-4, momentum=0.9)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
# Add evaluation metrics (for EVAL mode)
return tf.estimator.EstimatorSpec(mode=mode, loss=loss)
# Create the Estimator
estimator = tf.estimator.Estimator(
model_fn=model_fn,
model_dir="/tmp/discriminative_model"
)
def input_fn():
features, labels = create_synthetic_image()
training_data = tf.data.Dataset.from_tensors((features, labels))
training_data = training_data.repeat(None)
training_data = training_data.batch(1)
training_data = training_data.prefetch(1)
return training_data
estimator.train(input_fn=lambda: input_fn(), steps=2000)
eval_results = estimator.evaluate(input_fn=lambda: input_fn(), steps=50)
print('Eval loss at step %d: %s' % (eval_results['global_step'], eval_results['loss']))
每次都会创建相同的图像/标签。