基于TensorFlow深度学习框架,运用python搭建LeNet-5卷积神经网络模型和mnist手写数字识别数据集,设计一个手写数字识别软件
时间: 2024-03-02 20:54:13 浏览: 104
【深度学习】tensorflow 卷积神经网络 实现手写数字识别
好的,以下是基于TensorFlow深度学习框架,使用Python搭建LeNet-5卷积神经网络模型并使用MNIST手写数字识别数据集进行训练和测试的代码:
```
# 导入所需要的库
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# 将像素值归一化到[0, 1]之间
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# 将标签转换成one-hot编码
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
# 定义LeNet-5模型
model = keras.Sequential([
layers.Conv2D(filters=6, kernel_size=(5, 5), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(filters=16, kernel_size=(5, 5), activation='relu'),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dense(units=120, activation='relu'),
layers.Dense(units=84, activation='relu'),
layers.Dense(units=10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(x_train.reshape(-1, 28, 28, 1), y_train, batch_size=128, epochs=20, validation_split=0.2)
# 评估模型
score = model.evaluate(x_test.reshape(-1, 28, 28, 1), y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 绘制训练曲线
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
# 使用模型进行预测
predictions = model.predict(x_test.reshape(-1, 28, 28, 1))
for i in range(10):
print('Prediction:', np.argmax(predictions[i]))
print('True label:', np.argmax(y_test[i]))
plt.imshow(x_test[i], cmap='gray')
plt.show()
```
运行以上代码,将会得到一个基于LeNet-5模型的手写数字识别软件。该软件可以通过图形界面或命令行方式输入手写数字图片,自动识别出数字并显示在界面上。
阅读全文