机器学习 手写数字识别python代码
时间: 2024-06-22 11:04:07 浏览: 135
手写数字识别,手写数字识别python,Python
5星 · 资源好评率100%
机器学习中的手写数字识别是一个经典的应用场景,通常使用深度学习方法,如卷积神经网络(Convolutional Neural Networks, CNN)来完成。Python是实现这类任务的理想语言,因为它有强大的科学计算库如NumPy和Pandas,以及深度学习框架如TensorFlow或Keras。
以下是一个简单的概述和使用Keras库实现手写数字识别的步骤:
1. 导入必要的库:
```python
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
```
2. 加载MNIST数据集:
```python
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
```
3. 数据预处理(归一化和reshape):
```python
train_images = train_images.reshape((60000, 28, 28, 1)) / 255.0
test_images = test_images.reshape((10000, 28, 28, 1)) / 255.0
```
4. 定义模型结构(例如,简单的CNN模型):
```python
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
```
5. 编译模型:
```python
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
```
6. 训练模型:
```python
model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
```
7. 测试模型性能:
```python
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"Test accuracy: {test_acc}")
```
阅读全文