【发布时间】:2019-04-22 16:44:03
【问题描述】:
如何让经过训练的模型识别我从其他地方提取的图像?
模型使用 MNIST 数据集进行训练,图像 由模型识别的是从文档中提取的手写数字。
使用的库是tensorflow 2.0、cv2 和numpy。
据我了解,model.predict() 识别其输入。我的意思是,如果我在那里以某种形式输入“3”的手写图像,它将识别并输出“3”。同样,这表示 model 是使用基于 this set of tutorials 的 MNIST 数据集进行训练的。
假设是,我想知道函数的参数,或者我将如何格式化图像/图像集以获得预期的输出。如果没有,我想知道我将如何准确地做到这一点。
import cv2
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import keras
# Load and prepare the MNIST dataset. Convert the samples from integers to floating-point numbers:
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
def createModel():
# Build the tf.keras.Sequential model by stacking layers.
# Choose an optimizer and loss function used for training:
model = tf.keras.models.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
model = createModel()
model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
model.evaluate(x_test, y_test)
c = cv2.imread("./3.png", 1)
c = c.reshape(-1, 28*28)/255.0
# now what?
我预计 model.predict() 会按照我的需要进行操作。到目前为止,这是我的尝试:
model.predict(c) 输出TypeError: predict() missing 1 required positional argument: 'x'
model.predict([""], c) 输出ValueError: When using data tensors as input to a model, you should specify thestepsargument.
等等。
我知道此时我会盲目且错误地进入。朝着正确方向迈出的任何一步都值得赞赏。谢谢!
编辑:
所以我知道输入图像c 甚至在重塑之前应该是灰度 28x28,所以我尝试跳过它。我实现预测时出现的错误是:
...
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [28,28], In[1]: [784,128]
[[{{node dense/MatMul}}]] [Op:__inference_keras_scratch_graph_2593]
所以我在预测之前使用了c = c.reshape(-1, 28*28)/255.0,但它从未预测任何数字的正确值。
然后我尝试使用cv2.imshow(str(predicted_value), c) 来显示输入图像的外观。显示的图像只是黑色和白色斑点的细线。由于我还不能链接图片,请here is the link to the output 代替。
我的问题是,这是否是模型的图像应该看起来的样子?或者我可能搞砸了?谢谢!
【问题讨论】:
-
c的形状是什么? -
哦,我在示例代码中出错了。
txt应该是c,所以c应该是 1 通道 28 * 28 图像,与单个 MNIST 图像的形状相同。
标签: python tensorflow keras