将训练有素的Tensorflow模型加载到估算工具

时间:2018-01-10 16:25:09

标签: python tensorflow conv-neural-network tensorflow-estimator

说我已经训练过Tensorflow Estimator:

estimator = tf.contrib.learn.Estimator(
  model_fn=model_fn,
  model_dir=MODEL_DIR,
  config=some_config)

我适合一些火车数据:

estimator.fit(input_fn=input_fn_train, steps=None)

我的想法是模型适合我的MODEL_DIR。此文件夹包含一个检查点以及.meta.index的几个文件。

这完美无缺。我想用我的函数做一些预测:

estimator = tf.contrib.Estimator(
  model_fn=model_fn,
  model_dir=MODEL_DIR,
  config=some_config)

predictions = estimator.predict(input_fn=input_fn_test)

我的解决方案完美无缺,但有一个很大的缺点:你需要知道model_fn,这是我在Python中定义的模型。但是,如果我通过在Python代码中添加密集层来更改模型,则此模型对于MODEL_DIR中保存的数据不正确,从而导致不正确的结果:

NotFoundError (see above for traceback): Key xxxx/dense/kernel not found in checkpoint

我该如何应对?如何加载我的模型/估算器,以便我可以对一些新数据进行预测?如何从MODEL_DIR加载model_fn或估算器?

1 个答案:

答案 0 :(得分:1)

避免不良修复

仅在模型和检查点兼容的情况下,才能从检查点恢复模型的状态。例如,假设您培训了一个DNNClassifier Estimator,其中包含两个隐藏图层,每个图层包含10个节点:

classifier = tf.estimator.DNNClassifier(
    feature_columns=feature_columns,
    hidden_units=[10, 10],
    n_classes=3,
    model_dir='models/iris')

classifier.train(
    input_fn=lambda:train_input_fn(train_x, train_y, batch_size=100),
        steps=200)

训练后(因此,在models/iris中创建检查点后),想象您将每个隐藏层中的神经元数量从10更改为20,然后尝试重新训练模型:

classifier2 = tf.estimator.DNNClassifier(
    feature_columns=my_feature_columns,
    hidden_units=[20, 20],  # Change the number of neurons in the model.
    n_classes=3,
    model_dir='models/iris')

classifier.train(
    input_fn=lambda:train_input_fn(train_x, train_y, batch_size=100),
        steps=200)

由于检查点中的状态与classifier2中描述的模型不兼容,因此重新训练失败并出现以下错误:

...
InvalidArgumentError (see above for traceback): tensor_name =
dnn/hiddenlayer_1/bias/t_0/Adagrad; shape in shape_and_slice spec [10]
does not match the shape stored in checkpoint: [20]

要运行您训练和比较模型略有不同版本的实验,请保存创建每个model_dir的代码副本,可能是为每个版本创建一个单独的git分支。这种分离将使您的检查点可以恢复。

从张量流检查点doc。

复制

https://www.tensorflow.org/get_started/checkpoints

希望能帮助你。

相关问题