【问题标题】:Given a set of images to be identified, and a trained model, how would I make the model identify the images?给定一组要识别的图像和一个训练有素的模型,我如何让模型识别图像?
【发布时间】:2019-04-22 16:44:03
【问题描述】:

如何让经过训练的模型识别我从其他地方提取的图像?

模型使用 MNIST 数据集进行训练,图像 由模型识别的是从文档中提取的手写数字。

使用的库是tensorflow 2.0cv2numpy

据我了解,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


【解决方案1】:

当您的模型使用灰度图像进行训练时,它期望输入图像是灰度图像。 RGB 图像有 3 个通道。灰度图像只有 1 个通道。

因此,当加载图像时,而不是代表 cv2.IMREAD_COLOR1,请使用对应于 cv2.IMREAD_GRAYSCALE 的 0 以灰度模式加载图像。

(注意:使用 -1 表示 cv2.IMREAD_UNCHANGED 有关详细信息,请参阅 opencv 文档 here

yourimage = cv2.imread("yourimage.png", 0)

对于预测,整形后可以使用:

predicted_value = np.argmax(model.predict(yourimage))

【讨论】:

  • 谢谢!有效!然而,它从来没有一个数字是正确的。请在我的帖子中查看以下编辑,因为评论太长了。再次感谢您!
  • 预测的准确性是衡量您的神经网络架构有多好的指标,它还取决于您的训练/验证数据。您必须通过调整超参数(例如层数、层类型、学习率、优化器等)来调整您的神经网络,以便能够很好地泛化。在您的情况下,我认为 5 个 epoch 还不够该模型。尝试将其提高到 100 以上。您的验证准确度是多少?
  • 所以输入图像不是问题?顺便说一句,如果您所说的验证准确度是训练或加载权重后model.evaluate(x_test, y_test) 的输出,那么它至少是 0.97。我会试试你说的。谢谢!
猜你喜欢
  • 2019-12-07
  • 2018-06-25
  • 2023-04-02
  • 2012-09-17
  • 2019-10-30
  • 2016-04-03
  • 2021-07-01
  • 2017-12-16
  • 2020-10-17
相关资源
最近更新 更多