账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何使用tensorflow例程中训练好的 CNN MNIST 分类器来预测单个图片?
    65
    0

    问题描述

    我是机器学习新手,看过一些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?应该怎么改呢,求大牛指教,不胜感激。

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 娇而不傲的猫ヘ 普通会员 1楼

      在 TensorFlow 中,我们可以通过以下步骤来训练好的 CNN MNIST 分类器来预测单个图片:

      1. 导入必要的库和模块:

      python import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout

      1. 加载数据集:

      python (x_train, y_train), (x_test, y_test) = mnist.load_data()

      1. 数据预处理:

      ```python x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)

      x_train = x_train.astype('float32') / 255 x_test = x_test.astype('float32') / 255

      y_train = tf.keras.utils.to_categorical(y_train, 10) y_test = tf.keras.utils.to_categorical(y_test, 10) ```

      1. 创建 CNN 模型:

      python model = Sequential() model.add(Dense(128, activation='relu', input_shape=(28, 28, 1))) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax'))

      1. 编译模型:

      python model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

      1. 训练模型:

      python history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))

      1. 评估模型:

      python test_loss, test_acc = model.evaluate(x_test, y_test) print('Test accuracy:', test_acc)

      1. 使用模型进行预测:

      python predictions = model.predict(x_test)

      以上就是使用 TensorFlow 中训练好的 CNN MNIST 分类器来预测单个图片的基本步骤。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部