神经网络多层感知分类器实现手写数字识别?
时间: 2024-01-22 13:15:08 浏览: 133
以下是一个使用神经网络多层感知分类器实现手写数字识别的示例:
1. 导入所需的库和模块
```python
import tensorflow as tf
from tensorflow.keras import layers, models
```
2. 加载MNIST数据集并进行预处理
```python
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0
```
3. 构建多层感知分类器模型
```python
model = models.Sequential([
layers.Flatten(input_shape=(28, 28)),
layers.Dense(128, activation='relu'),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
```
4. 编译模型并训练
```python
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
```
5. 评估模型性能
```python
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
```
阅读全文