No model.pb or model.pbtxt
I used ML Engine to tune hyperparameters on a model. When the trials complete there are 5 folders with .cktp files and graph.pbtxt but no model.pb or model.pbtxt file.
%%writefile hyperparam.yaml
trainingInput:
hyperparameters:
goal: MINIMIZE
maxTrials: 5
maxParallelTrials: 1
hyperparameterMetricTag: average_loss
params:
- parameterName: batch_size
type: INTEGER
minValue: 8
maxValue: 64
scaleType: UNIT_LINEAR_SCALE
- parameterName: learning_rate
type: DOUBLE
minValue: 0.01
maxValue: 0.1
scaleType: UNIT_LOG_SCALE
%%bash
OUTDIR=gs://${BUCKET}/breastCancer_trained
gsutil rm -rf $OUTDIR
gcloud ml-engine jobs submit training breastCancer_$(date -u +%y%m%d_%H%M%S) \
--config=hyperparam.yaml \
--module-name=trainer.breastCancer \
--package-path=$(pwd)/trainer \
--job-dir=$OUTDIR \
--runtime-version=$TFVERSION \
I want to import the optimized model using tf.contrib.predictor.from_saved_model() which requires a model.pb or model.pbtxt file.
Hi, let's try to get this resolved.
Did you happen to add code to your model file that saves the graph and exports it to GCS?
Hi - Please make sure that yo have the following:
- serving_fn - to accept data points for predictions
- FinalExporter - and give it a name and the serving_fn
- TrainSpec & EvalSpec - the EvalSpec takes the exporter as a parameter
- tf.estimator.train_and_evaluate() - which takes your estimator, TrainSpec, and EvalSpec
The example here show all of these components. The output should be: <model_dir>/<trail_number>/export/<exporter_name>/<numeric_identifier>/model.pb
Here is my code:
train_input_fn = tf.estimator.inputs.pandas_input_fn(x = df_train[FEATURES],
y = df_train[LABEL],
num_epochs = 1,
batch_size = batch_size, # note the batch size
shuffle = True)
eval_input_fn = tf.estimator.inputs.pandas_input_fn(x = df_eval[FEATURES],
y = df_eval[LABEL],
num_epochs = 1,
batch_size = len(df_eval),
shuffle=False)
# Define feature columns
#features = [tf.feature_column.numeric_column('num_rooms')]
def train_and_evaluate(output_dir):
# Compute appropriate number of steps
num_steps = (len(df_train) / batch_size) / learning_rate # if learning_rate=0.01, hundred epochs
# Create custom optimizer
myopt = tf.train.FtrlOptimizer(learning_rate = learning_rate) # note the learning rate
estimator = tf.estimator.DNNClassifier(feature_columns = make_feature_cols(), model_dir = output_dir, hidden_units=[10, 10], n_classes=2,optimizer = myopt)
train_spec = tf.estimator.TrainSpec(input_fn = train_input_fn,
max_steps = num_steps)
eval_spec = tf.estimator.EvalSpec(input_fn = eval_input_fn,
steps = None)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
def make_feature_cols():
input_columns = [tf.feature_column.numeric_column(k) for k in FEATURES]
return input_columns
# Run the training
shutil.rmtree(output_dir, ignore_errors=True) # start fresh each time
train_and_evaluate(output_dir)
if __name__ == '__main__' and "get_ipython" not in dir():
parser = argparse.ArgumentParser()
parser.add_argument(
'--learning_rate',
type = float,
default = 0.01
)
parser.add_argument(
'--batch_size',
type = int,
default = 30
),
parser.add_argument(
'--job-dir',
help = 'GCS location to write checkpoints and export models.',
required = True
)
args = parser.parse_args()
print("Writing checkpoints to {}".format(args.job_dir))
train(args.job_dir, args.batch_size, args.learning_rate)
I do not have a service_fn or exporter. Is that a requirement for ML Engine to generate a model.pb file?
I modified the example from here: https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive/05_artandscience/b_hyperparam.ipynb
The help line ' help = 'GCS location to write checkpoints and export models.' implies ML Engine automatically saves the model.pb file.
@mtm12 - Exporting the model is irrelevant to MLE. You need to have a serving_fn and and exporter in your EvalSpec so that the your model is exported at the end of the training (using the FinalExporter). Training your model without these things locally, on Cloud MLE (with or without HP tuning) will not export your model to SavedModel.pb. The reason why this code is not included in the example that you mentioned might be the following: a common pattern is to run HP tuning experiment with a subset of the data and without exporting the models. After you find the best config of HP, you run a training experiment using the whole dataset, and specifying the exporter in the EvalSpec to produce the SavedModel.pb to be served.
I actually did have the serving_fn and exporter in my original code running on my local machine. I didn't realize how that interacted with MLE. This works:
feature_spec = tf.feature_column.make_parse_example_spec(feature_columns);
export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec);
model.export_savedmodel(OUTDIR, export_input_fn, as_text=False)