Проблема на получение прогнозов от обученного CNN tf.estimator - PullRequest
0 голосов
/ 03 мая 2019

Я новичок в tenorflow.Я следую за учебником.И я взял код учебного пособия по тензорному потоку cnn , и я обучил модель CNN.Я пытаюсь использовать эту модель и estimator.predict, чтобы предсказать одно изображение вне тестового набора и обучающего набора. Но я сталкиваюсь с некоторыми проблемами (Восстановление из контрольной точки не удалось.)

Я добавляю свой код в основную функцию.модель уже обучена, поэтому я пропустил обучающий код здесь.

def main(unused_argv):
    # Load training and eval data
    mnist = tf.contrib.learn.datasets.load_dataset("mnist")
    train_data = mnist.train.images  # Returns np.array
    train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
    eval_data = mnist.test.images  # Returns np.array
    eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

    # Create the Estimator
    mnist_classifier = tf.estimator.Estimator(  # mnist_classifier
        model_fn=cnn_model_fn, model_dir="models/cnn")

    # Set up logging for predictions
    # Log the values in the "Softmax" tensor with label "probabilities"
    tensors_to_log = {"probabilities": "softmax_tensor"}
    logging_hook = tf.train.LoggingTensorHook(
        tensors=tensors_to_log, every_n_iter=50)

    # # Train the model  The model is already trained so I have skipped the training code here
    # train_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn(
    #     x={"x": train_data},
    #     y=train_labels,
    #     batch_size=100,
    #     num_epochs=None,
    #     shuffle=True)
    # mnist_classifier.train(
    #     input_fn=train_input_fn,
    #     steps=20000,  # 20000
    #     hooks=[logging_hook])
    #
    # # Evaluate the model and print results
    # eval_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn(
    #     x={"x": eval_data}, y=eval_labels, num_epochs=1, shuffle=False)
    # eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
    # print(eval_results)

    #predict_data = eval_data[1]

    #here is my code
    predict_data = np.random.rand(784) #this random list representsa 784 pixel image
    predict_data = np.array(predict_data)
    predict_data = np.reshape(predict_data, (1, 784))

    pred_input_fn = tf.estimator.inputs.numpy_input_fn(
        x={"x": predict_data},
        shuffle=False)

    pred_results = mnist_classifier.predict(input_fn=pred_input_fn)
    print(next(pred_results))


if __name__ == "__main__":
    tf.app.run()

здесь есть ошибка

InvalidArgumentError (see above for traceback): Restoring from checkpoint failed. This is most likely due to a mismatch between the current graph and the graph from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. 

Но это хорошо работает, если я использую изображение, которое уже находится в тестовом наборе.

predict_data = eval_data[1]
predict_data = np.reshape(predict_data, (1, 784))

Что я должен сделать, чтобы этот режим предсказывал на одном изображении вне тестового набора и обучающего набора?

Буду признателен за любую дополнительную помощь.

...