tensorflow - 如何清理图像以与 MNIST 训练模型一起使用?

标签 tensorflow machine-learning keras image-recognition mnist

我正在创建一个机器学习模型来对数字图像进行分类。我使用 Tensorflow 和 Keras 使用内置的 tf.keras.datasets.mnist 数据集训练了模型。该模型与 mnist 数据集本身的测试图像配合得很好,但我想向它提供我自己的图像。我为该模型提供的图像是从验证码中提取的,因此它们将遵循类似的模式。我在 this 中包含了一些图像示例公共(public)谷歌驱动器文件夹。当我输入这些图像时,我注意到模型不是很准确,我对原因有一些猜测。

  1. 图像的背景在图片中产生了过多的噪点。
  2. 数字未居中。
  3. 图像不严格遵守 MNIST 训练集的颜色格式(黑底白字)。

我想问如何删除背景并将其居中,以便减少图像中的噪声,从而实现更好的分类。

这是我正在使用的模型:

import tensorflow as tf
from tensorflow import keras

mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

class Stopper(keras.callbacks.Callback):
    def on_epoch_end(self, epoch, log={}):
        if log.get('acc') >= 0.99:
            self.model.stop_training = True
            print('\nReached 99% Accuracy. Stopping Training...')

model = keras.Sequential([
    keras.layers.Flatten(),
    keras.layers.Dense(1024, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)])

model.compile(
    optimizer=tf.train.AdamOptimizer(),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'])

x_train, x_test = x_train / 255, x_test / 255

model.fit(x_train, y_train, epochs=10, callbacks=[Stopper()])

这是我将图像导入到tensorflow的方法:

from PIL import Image
img = Image.open("image_file_path").convert('L').resize((28, 28), Image.ANTIALIAS)
img = np.array(img)
model.predict(img[None,:,:])

我还包含了 MNIST 数据集 here 中的一些示例。我想要一个脚本将我的图像转换为尽可能接近 MNIST 数据集格式。另外,由于我必须对无限数量的图像执行此操作,因此如果您能为这种转换提供完全自动化的方法,我将不胜感激。非常感谢。

最佳答案

您需要使用与您正在测试的图像类似的数据集进行训练。 MNIST 数据是手写数字,与计算机生成的验证码数据字体不同。

您需要做的是获取与您预测的验证码数据类似的目录(最好来自您将输入最终模型的同一来源)。捕获数据是一项艰巨的任务,每个标签可能需要大约 300-400 张图像,然后才能开始获得有用的信息。

重要说明:您的模型的好坏取决于您提供给模型的训练数据。尝试用糟糕的训练数据建立一个好的模型纯粹是一种挫败感

解决您的一些想法:

[the model is not very accurate because] the background of the image creates too much noise in the picture.

这是真的。如果图像数据有噪声,并且神经网络没有使用图像中的任何噪声进行训练,那么当遇到这种类型的失真时,它将无法识别出强模式。解决这个问题的一种可能方法是拍摄干净的图像,并在发送图像进行训练之前以编程方式向图像添加噪声(类似于您在真实验证码中看到的噪声)。

[the model is not very accurate because] The number is not centered.

出于同样的原因也是如此。如果所有训练数据都集中,模型将针对此属性进行过度调整并做出错误的猜测。如果您没有能力手动捕获和编目大量数据样本,请遵循与上述类似的模式。

[the model is not very accurate because] The image is not striclty in the color format of MNIST training set (Black background white text).

您可以通过在处理之前对数据应用二进制阈值/在训练之前对颜色输入进行标准化来解决此问题。根据验证码中的噪声量,您可能会得到更好的结果,允许数字和噪声保留一些颜色信息(仍然放入灰度并标准化,只是不应用阈值)。

<小时/>

此外,我建议使用卷积网络而不是线性网络,因为它可以更好地区分边缘和角点等 2D 特征。即使用 keras.layers.Conv2D压平之前的层 keras.layers.Flatten

请参阅此处找到的优秀示例:Trains a simple convnet on the MNIST dataset.

model = tf.keras.models.Sequential(
    [
        tf.keras.layers.Conv2D(
            32,
            kernel_size=(3, 3),
            activation=tf.nn.relu,
            input_shape=input_shape,
        ),
        tf.keras.layers.Conv2D(64, (3, 3), activation=tf.nn.relu),
        tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
        tf.keras.layers.Dropout(0.25),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(128, activation=tf.nn.relu),
        tf.keras.layers.Dropout(0.5),
        tf.keras.layers.Dense(
            num_classes, activation=tf.nn.softmax
        ),
    ]
)

我已经使用此设置来读取视频游戏片段中的字体,并且通过 10,000 张图像的测试集,我在训练中使用一半数据集的随机采样,并使用总数计算准确性,达到了 99.98% 的准确率设置。

关于tensorflow - 如何清理图像以与 MNIST 训练模型一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57000160/

相关文章:

python - Tensorflow — 使用 `tf.keras.Model.add_metric` 时无法调用 `tf.distribute.MirroredStrategy`

python - 如何在keras中使用一维卷积神经网络解决音频信号问题

matlab - 判别分析方法对数据进行分类

python - 如何将参数传递给已加载的 tensorflow 图(在内存中)

python-3.x - 如何通过在 36x60 大小的数据上训练的神经网络预测不同的数据?

python - Keras (tensorflow) 找到 GPU,但只在 cpu w/Cuda 10.1 上运行

python - 哪种是进行图像标准化的正确方法?

python - Windows 10、RTX 2070] : Failed to get convolution algorithm

machine-learning - 用于计算 k 最近邻的距离度量

python - Tensorflow InvalidArgumentError : 2 root error(s) found. 索引 [28,0] = 11292 不在 [0, 11272)