问题描述
我是机器学习新手,看过一些ml的公开课,最近在跟着tensorflow的官方教程学习和实战。
我跟着官方的这个例程已经能够训练出一个识别手写数字的cnn模型了。但是当我想把它拓展一下,让模型识别其他的手写数字图片的时候遇到了难题。
我希望通过estimator.predict这个方法使用训练好的cnn模型,来对其他的手写数字图片进行预测。但是我发现只有传入已经存在于训练集或测试集里面的数据才能顺利预测,一旦传入任意其他的图片数据他就会报错。
相关代码
我自己添加的代码在官方例程中的main尾部,其他都和官方的代码一样。因为在我的电脑上已经训练过模型了,所以我把下面代码的训练部分注释掉了。
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
# 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]
#我添加的代码
predict_data = np.random.rand(784) #this random list represents 784 pixel image
predict_data = np.array(predict_data)
predict_data = np.reshape(predict_data, (1, 784))
# predict_data = eval_data[1]
# 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()
我发现只要我像这样传入其他图片就会报错
predict_data = np.random.rand(784) #this random list represents 784 pixel image
predict_data = np.array(predict_data)
predict_data = np.reshape(predict_data, (1, 784))
错误代码
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))
我不知道为什会这样,会不会是我思路错了,不能使用predict?应该怎么改呢,求大牛指教,不胜感激。