在Tensorflow的估算器中,当多次调用model_fn时它是如何工作的?

时间:2017-10-22 03:23:28

标签: tensorflow tensorflow-datasets

def model_fn(features, labels, mode, params):
  """Model function for Estimator."""

  # Connect the first hidden layer to input layer
  # (features["x"]) with relu activation
  first_hidden_layer = tf.layers.dense(features["x"], 10, activation=tf.nn.relu)

  # Connect the second hidden layer to first hidden layer with relu
  second_hidden_layer = tf.layers.dense(
      first_hidden_layer, 10, activation=tf.nn.relu)

  # Connect the output layer to second hidden layer (no activation fn)
  output_layer = tf.layers.dense(second_hidden_layer, 1)

  # Reshape output layer to 1-dim Tensor to return predictions
  predictions = tf.reshape(output_layer, [-1])

  # Provide an estimator spec for `ModeKeys.PREDICT`.
  if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(
        mode=mode,
        predictions={"ages": predictions})

  # Calculate loss using mean squared error
  loss = tf.losses.mean_squared_error(labels, predictions)

  # Calculate root mean squared error as additional eval metric
  eval_metric_ops = {
      "rmse": tf.metrics.root_mean_squared_error(
          tf.cast(labels, tf.float64), predictions)
  }

  optimizer = tf.train.GradientDescentOptimizer(
      learning_rate=params["learning_rate"])
  train_op = optimizer.minimize(
      loss=loss, global_step=tf.train.get_global_step())

  # Provide an estimator spec for `ModeKeys.EVAL` and `ModeKeys.TRAIN` modes.
  return tf.estimator.EstimatorSpec(
      mode=mode,
      loss=loss,
      train_op=train_op,
      eval_metric_ops=eval_metric_ops)

以上是Tensorflow Estimator使用的model_fn示例。

如教程中所述,可以在不同的上下文(训练,预测,评估)中调用此model_fn。但是,我有点困惑,因为每次调用model_fn时,而不是重用现有图形,它似乎创建了一个新图形(或在图形中创建新节点)

例如,首先我在TRAIN模式下调用了model_fn,然后用PREDICT模式调用了model_fn。如何确保PREDICT重复使用训练值的权重?

1 个答案:

答案 0 :(得分:0)

请参阅此主题:https://github.com/tensorflow/tensorflow/issues/13895

每次重建图表,并从检查点加载数据。