python - 如何使用 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)
解决方案
您可以按如下方式使用model
对象的方法:.predict()
import numpy as np
predictions = model.predict([x_test]) # Make prediction
print(np.argmax(predictions[1000])) # Print out the number
无论如何,我建议你学习一个简单的例子,说明如何使用 tensorflow 对 Abdelhakim Ouafi 的手写数字进行分类。如果链接可用,我在这里为未来的读者提供主要部分:
MNIST 手写数字的描述。
MNIST Handwritten Digit 是一个用于评估机器学习和深度学习模型在手写数字分类问题上的数据集,它是一个包含 0 到 9 之间的 60,000 个小正方形 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)和测试数据集(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
在我们将数据输入神经网络之前,我们需要通过在 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 子包,并将训练数据和与训练数据集相对应的标记数据提供给它,以及应该运行多少 epoch 或应该猜测多少次。
model.fit(x=x_train, y=y_train, epochs=5) # Start training process
# 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 个 epoch 训练了模型。
进行预测 现在,我们将通过导入测试数据集图像开始进行预测。
predictions = model.predict([x_test]) # Make prediction
我们将对模型从未见过的数字或图像进行预测。
例如,我们尝试预测与测试数据集中图像编号 1000 对应的数字:
print(np.argmax(predictions[1000])) # Print out the number
如您所见,预测是第 9 位,但我们如何确保该预测是正确的呢?好吧,我们需要使用 matplotlib 在测试数据集中绘制第 1000 个图像:
plt.imshow(x_test[1000], cmap="gray") # Import the image
plt.show() # Show the image
推荐阅读
- java - java.lang.IllegalStateException:没有合适的构造函数:
- c# - 从 .NET Core Web API POST 方法中调用外部 Web 服务
- javascript - 如何在 VSCode 中显示来自 JS 文件的内联源映射的源代码?
- django - 由于在 django 中更改应用程序名称,virtualenv 引发 importerror
- c++ - 使用 make libnl 对 linux 进行“未定义的引用”
- python - 设置梯度下降过程
- android - Android 整理 Intent 调用父级的 onCreate()
- c# - 每个 nameof() 用自己的名称初始化只读字符串的缺点?
- javascript - WebRtc 远程流未在 Web 中呈现
- git - 如何在 Atom 中使用 git 的编辑器?