神经网络之手写数字识别
时间: 2023-12-30 20:04:34 浏览: 30
神经网络在手写数字识别中被广泛应用。下面是一个简单的例子来演示神经网络如何进行手写数字识别:
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train / 255.0
x_test = x_test / 255.0
# 构建神经网络模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5)
# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
# 使用模型进行预测
predictions = model.predict(x_test)
```
这个例子使用了TensorFlow库来构建一个简单的神经网络模型,该模型包含一个输入层、一个隐藏层和一个输出层。模型通过训练MNIST数据集来学习手写数字的特征,并使用softmax函数来进行分类预测。