基于人工神经网络的数字识别。用python编程,用基于人工神经网络的数字识别解决一个问题,写出完整代码。(要求能在python3.13上运行)
时间: 2024-11-25 08:32:35 浏览: 16
基于人工神经网络的数字识别通常用于手写字符识别,例如MNIST数据集是一个常用的训练模型的数据源。以下是一个简化的例子,使用Python的Keras库来实现一个简单的卷积神经网络(Convolutional Neural Network,CNN),它能对MNIST数据集进行分类:
```python
# 导入必要的库
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# 加载并预处理MNIST数据集
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
train_images, test_images = train_images / 255.0, test_images / 255.0
# 定义模型结构
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Flatten(), # 展平卷积层输出
layers.Dense(64, activation='relu'),
layers.Dropout(0.2),
layers.Dense(10)
])
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 训练模型
history = model.fit(train_images, train_labels, epochs=10, validation_split=0.2)
# 评估模型性能
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
# 显示一些预测结果
predictions = model.predict(test_images[:10])
for i in range(10):
plt.imshow(test_images[i], cmap=plt.cm.binary)
plt.show()
predicted_label = np.argmax(predictions[i])
true_label = test_labels[i]
print(f"Predicted label: {predicted_label}, True label: {true_label}")
阅读全文