如何使用Keras模型进行手写字符识别的预测

时间:2019-12-14 09:40:26

标签: python tensorflow keras

我们已经有训练有素的模型,但是我们无法编写程序中进行预测的部分。我们可以打开图片,但无法使用TensorFlow进行处理。

任何帮助将不胜感激。这就是我们已经拥有的。

 from __future__ import absolute_import, division, print_function, unicode_literals

# Install TensorFlow

import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='tanh'),    #relu, softmax, tanh
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='tanh')
])

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

model.fit(x_train, y_train, epochs=5)

model.evaluate(x_test,  y_test, verbose=2)

1 个答案:

答案 0 :(得分:0)

您可以如下使用model对象的.predict()方法:

import numpy as np

predictions = model.predict([x_test]) # Make prediction
print(np.argmax(predictions[1000])) # Print out the number

无论如何,我建议您研究nice, simple example,有关如何使用Tensorflow对Abdelhakim Ouafi的手写数字进行分类。如果链接可用,我将在此处包括该案例的主要部分,以供将来的读者阅读:

MNIST手写数字的说明。

MNIST手写数字是用于评估针对手写数字分类问题的机器学习和深度学习模型的数据集,它是6万个介于0到9之间的手写数字的小正方形28×28像素灰度图像的数据集。

导入TensorFlow库

import tensorflow as tf # Import tensorflow library
import matplotlib.pyplot as plt # Import matplotlib library

创建一个名为mnist的变量,并将其设置为Keras库中MNIST数据集的对象,然后我们将其解压缩为训练数据集(x_train,y_train)并测试数据集< strong>(x_test,y_test):

mnist = tf.keras.datasets.mnist # Object of the MNIST dataset
(x_train, y_train),(x_test, y_test) = mnist.load_data() # Load data

预处理数据

为确保正确导入我们的数据,我们将使用matplotlib从训练数据集中绘制第一张图像:

plt.imshow(x_train[0], cmap="gray") # Import the image
plt.show() # Plot the image

enter image description here

在将数据输入到神经网络之前,我们需要通过将像素值缩放为0到1(而不是0到255)来对其进行归一化,这使得神经网络需要更少的计算能力:

# Normalize the train dataset
x_train = tf.keras.utils.normalize(x_train, axis=1)
# Normalize the test dataset
x_test = tf.keras.utils.normalize(x_test, axis=1)

构建模型 现在,我们将建立模型,或者换句话说,就是将训练和学习如何对这些图像进行分类的神经网络。

值得注意的是,在构建人工神经网络时,图层是最重要的,因为它将提取数据的特征。

首先,我们首先创建一个模型对象,让您添加不同的图层。

第二,在这种情况下,我们将对数据进行展平。因此图像是28×28尺寸,我们需要将其设置为1×784尺寸,以便神经网络的输入层可以读取或处理它。这是您需要知道的重要概念。

第三,我们定义输入和一个具有128个神经元的隐藏层以及一个激活功能,即relu函数。

最后,我们创建具有10个神经元和一个softmax激活函数的输出层,该函数将模型返回的分数转换为一个值,以便人类进行解释。

#Build the model object
model = tf.keras.models.Sequential()
# Add the Flatten Layer
model.add(tf.keras.layers.Flatten())
# Build the input and the hidden layers
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
# Build the output layer
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

编译模型 自完成神经网络的构建以来,我们需要通过添加一些参数来编译模型,这些参数将告诉神经网络如何开始训练过程。

首先,我们添加优化器,该优化器将创建或换句话说更新神经网络的参数以适合我们的数据。

第二,损失函数将告诉您模型的性能。

第三,用于指示模型质量的指标测试。

# Compile the model
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

训练模型 我们已经准备好训练模型,我们将其称为fit子包,并为其提供训练数据和与训练数据集相对应的标记数据,以及应该运行多少个时期或应该进行多少次猜测。

model.fit(x=x_train, y=y_train, epochs=5) # Start training process

enter image description here 评估模型 让我们看看训练过程完成后模型的表现。

# Evaluate the model performance
test_loss, test_acc = model.evaluate(x=x_test, y=y_test)
# Print out the model accuracy 
print('\nTest accuracy:', test_acc)

评估模型性能 结果表明神经网络的准确率达到了97.39%,这是非常好的,因为我们只用5个时间段来训练模型。

做出预测 现在,我们将通过导入测试数据集图像开始进行预测。

predictions = model.predict([x_test]) # Make prediction

我们将对模型从未见过的数字或图像进行预测。

例如,我们尝试预测与测试数据集中的图像编号1000相对应的编号:

print(np.argmax(predictions[1000])) # Print out the number

Prediction

如您所见,该预测是第九位,但是我们如何确保该预测是正确的?好,我们需要使用matplotlib在测试数据集中绘制图像编号1000:

plt.imshow(x_test[1000], cmap="gray") # Import the image
plt.show() # Show the image

enter image description here