- 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 条
- 全部回答
-
娇而不傲的猫ヘ 普通会员 1楼
在 TensorFlow 中,我们可以通过以下步骤来训练好的 CNN MNIST 分类器来预测单个图片:
- 导入必要的库和模块:
python import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout- 加载数据集:
python (x_train, y_train), (x_test, y_test) = mnist.load_data()- 数据预处理:
```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) ```
- 创建 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'))- 编译模型:
python model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])- 训练模型:
python history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))- 评估模型:
python test_loss, test_acc = model.evaluate(x_test, y_test) print('Test accuracy:', test_acc)- 使用模型进行预测:
python predictions = model.predict(x_test)以上就是使用 TensorFlow 中训练好的 CNN MNIST 分类器来预测单个图片的基本步骤。
- 扫一扫访问手机版
回答动态

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器更新之后。服务器里面有部分玩家要重新创建角色是怎么回事啊?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题函数计算不同地域的是不能用内网吧?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题ARMS可以创建多个应用嘛?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题在ARMS如何申请加入公测呀?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题前端小程序接入这个arms具体是如何接入监控的,这个init方法在哪里进行添加?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器刚到期,是不是就不能再导出存档了呢?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器的游戏版本不兼容 尝试更新怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器服务器升级以后 就链接不上了,怎么办?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器转移以后服务器进不去了,怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器修改参数后游戏进入不了,是什么情况?预计能赚取 0积分收益
- 回到顶部
- 回到顶部

