【发布时间】:2019-03-13 00:02:30
【问题描述】:
我有以下示例代码来使用 tensorflow 的 estimator api 训练和评估一个 cnn mnist 模型:
def model_fn(features, labels, mode):
images = tf.reshape(features, [-1, 28, 28, 1])
model = Model()
logits = model(images)
predicted_logit = tf.argmax(input=logits, axis=1, output_type=tf.int32)
if mode == tf.estimator.ModeKeys.PREDICT:
probabilities = tf.nn.softmax(logits)
predictions = {
'predicted_logit': predicted_logit,
'probabilities': probabilities
}
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
else:
...
def mnist_train_and_eval(_):
train_data, train_labels, eval_data, eval_labels, val_data, val_labels = get_mnist_data()
# Create a input function to train
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x= train_data,
y=train_labels,
batch_size=_BATCH_SIZE,
num_epochs=1,
shuffle=True)
# Create a input function to eval
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
x= eval_data,
y=eval_labels,
batch_size=_BATCH_SIZE,
num_epochs=1,
shuffle=False)
# Create a estimator with model_fn
image_classifier = tf.estimator.Estimator(model_fn=model_fn, model_dir=_MODEL_DIR)
# Finally, train and evaluate the model after each epoch
for _ in range(_NUM_EPOCHS):
image_classifier.train(input_fn=train_input_fn)
metrics = image_classifier.evaluate(input_fn=eval_input_fn)
我如何使用 estimator.export_savedmodel 来保存经过训练的模型以供以后推断? serving_input_receiver_fn 应该怎么写?
非常感谢您的帮助!
【问题讨论】:
标签: tensorflow mnist