Python 手写数字识别

Python 手写数字识别

手写数字识别是机器学习和计算机视觉领域中的一个经典任务。我们将使用Python和一些常见的机器学习库(如TensorFlow和Keras)来实现一个简单的手写数字识别模型。本文将详细介绍整个过程,包括数据准备、模型构建、训练和评估。最终,我们将对我们的模型进行测试,看看它的性能如何。

目录

  1. 简介
  2. 数据准备
  3. 构建和训练模型
  4. 模型评估
  5. 模型测试
  6. 总结

简介

手写数字识别是指通过算法识别手写数字图像中包含的数字。常用的数据集是MNIST数据集,该数据集包含了从0到9的手写数字图像,每张图像大小为28x28像素。我们将使用TensorFlow和Keras框架来构建一个简单的卷积神经网络(CNN),以实现对手写数字的识别。

数据准备

我们首先需要下载并准备好MNIST数据集。TensorFlow提供了方便的接口来加载这个数据集。

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical

# 加载MNIST数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 数据标准化
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255

# 将标签转换为one-hot编码
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

print(f'Training data shape: {train_images.shape}')
print(f'Testing data shape: {test_images.shape}')

构建和训练模型

我们将使用Keras构建一个卷积神经网络(CNN)模型。这个模型将包含两个卷积层和两个全连接层。

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense

# 构建模型
model = Sequential([
    Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)),
    MaxPooling2D(pool_size=(2, 2)),
    Conv2D(64, kernel_size=(3, 3), activation='relu'),
    MaxPooling2D(pool_size=(2, 2)),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')
])

# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# 训练模型
history = model.fit(train_images, train_labels, epochs=5, batch_size=128, validation_split=0.2)

模型评估

在训练结束后,我们可以使用测试数据集来评估模型的性能。

# 评估模型
test_loss, test_accuracy = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_accuracy:.4f}')

模型测试

我们可以使用一些测试图像来测试我们的模型。下面的代码展示了如何在单张图像上使用训练好的模型进行预测。

import numpy as np

# 从测试集中选择一个样本
sample_image = test_images[0].reshape(1, 28, 28, 1)

# 预测
prediction = model.predict(sample_image)
predicted_label = np.argmax(prediction)

print(f'Predicted label: {predicted_label}')
print(f'Actual label: {np.argmax(test_labels[0])}')

总结

我们使用TensorFlow和Keras构建了一个简单的卷积神经网络模型来识别手写数字。我们从数据准备开始,构建并训练了模型,然后评估了模型的性能,并使用测试图像进行了预测。我们的模型在手写数字识别任务上取得了不错的效果。

希望这篇博客能帮助你更好地理解如何使用Python和机器学习库来构建手写数字识别模型。如果你有任何问题或建议,欢迎在下方留言。

感谢阅读!

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zw_Loneranger

你的鼓励是将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值