基于bp神经网络的手写数字识别的代码
时间: 2023-11-30 10:01:13 浏览: 89
基于bp神经网络的手写数字识别的代码如下:
首先,我们导入需要的库和模块:
```python
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.datasets import mnist
```
接下来,加载MNIST数据集并进行预处理:
```python
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(-1, 28*28) / 255.0
X_test = X_test.reshape(-1, 28*28) / 255.0
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)
```
然后,构建bp神经网络模型:
```python
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dense(units=10, activation='softmax')
])
```
定义优化器、损失函数和评估指标:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=['accuracy'])
```
接着,进行模型的训练与评估:
```python
model.fit(X_train, y_train, epochs=10, batch_size=128, verbose=1)
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', test_loss)
print('Test accuracy:', test_accuracy)
```
最后,我们可以使用训练好的模型对手写数字进行识别:
```python
image = plt.imread('test_image.png')
image = image.reshape(-1, 28*28) / 255.0
prediction = model.predict(image)
digit = np.argmax(prediction)
print('Predicted digit:', digit)
```
以上就是基于bp神经网络的手写数字识别的代码。
阅读全文