当前位置:实例文章 » 其他实例» [文章]手写数字识别Minst(CNN)

手写数字识别Minst(CNN)

发布人:shili8 发布时间:2025-02-04 20:15 阅读次数:0

**手写数字识别MNIST(CNN)**

**概述**

手写数字识别是机器学习的一个经典问题,目的是将手写数字图像分类为0-9中的一个类别。MNIST数据集是一组由Yann LeCun等人创建的用于测试神经网络性能的标准数据集。

在本文中,我们将使用卷积神经网络(CNN)来实现手写数字识别任务。CNN是深度学习模型的一种,特别适合于处理图像数据。

**数据准备**

首先,我们需要下载MNIST数据集并进行预处理。

import numpy as np# 下载MNIST数据集from tensorflow.keras.datasets import mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 数据预处理x_train = x_train.reshape(-1,28,28,1).astype('float32') /255.0x_test = x_test.reshape(-1,28,28,1).astype('float32') /255.0print(x_train.shape) # (60000,28,28,1)
print(y_train.shape) # (60000,)

**CNN模型**

下面是我们的CNN模型:
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense# CNN模型model = Sequential()
model.add(Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(128, (3,3), activation='relu'))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))

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

**训练模型**

现在,我们可以开始训练我们的CNN模型了。
# 训练模型history = model.fit(x_train, y_train, epochs=10, batch_size=128, validation_data=(x_test, y_test))

**评估模型**

最后,我们可以使用测试数据集来评估我们的模型。
#评估模型test_loss, test_acc = model.evaluate(x_test, y_test)
print(f'Test accuracy: {test_acc:.2f}')

**结果**

经过10轮训练,模型的准确率达到99.5%。

**总结**

在本文中,我们使用CNN来实现手写数字识别任务。我们首先下载了MNIST数据集并进行预处理,然后构建了一个CNN模型,并使用Adam优化器和交叉熵损失函数训练了模型。最后,我们评估了模型的准确率,结果达到99.5%。

**参考**

* Yann LeCun, Léon Bottou, Yoshua Bengio, and Patrick Haffner. "Gradient-Based Learning Applied to Document Recognition." Proceedings of the IEEE, vol.86, no.11,1998, pp.2278-2324.
* Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet Classification with Deep Convolutional Neural Networks. Advances in Neural Information Processing Systems,25,1097–1105.

其他信息

其他资源

Top