python实现对MNIST数据集的手写数字分类
时间: 2023-12-13 10:33:01 浏览: 105
以下是使用Python实现对MNIST数据集的手写数字分类的步骤:
1. 导入必要的库和数据集
```python
import tensorflow as tf
from tensorflow import keras
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
```
2. 数据预处理
```python
train_images = train_images / 255.0
test_images = test_images / 255.0
```
3. 构建模型
```python
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
```
4. 编译模型
```python
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
```
5. 训练模型
```python
model.fit(train_images, train_labels, epochs=10)
```
6. 评估模型
```python
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
```
7. 进行预测
```python
predictions = model.predict(test_images)
```