基于Keras搭建一个LeNet-5网络,实现对Mnist手写数字的识别
时间: 2023-12-08 17:04:55 浏览: 92
好的,我可以为您提供该问题的代码实现。以下是基于Keras搭建的LeNet-5网络对Mnist手写数字进行识别的代码:
```python
# 导入所需的库
from keras.layers import Conv2D, AveragePooling2D, Flatten, Dense
from keras.models import Sequential
from keras.datasets import mnist
from keras.utils import np_utils
# 载入数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 数据预处理
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32')
X_train /= 255
X_test /= 255
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# 构建模型
model = Sequential()
model.add(Conv2D(filters=6, kernel_size=(5,5), activation='relu', input_shape=(28,28,1)))
model.add(AveragePooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=16, kernel_size=(5,5), activation='relu'))
model.add(AveragePooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(units=120, activation='relu'))
model.add(Dense(units=84, activation='relu'))
model.add(Dense(units=10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=128, epochs=10)
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
在运行代码后,您将会得到模型的测试准确率,该模型可以识别0-9手写数字。
阅读全文