卷积神经网络实现手写数字图像识别 不用框架 附代码
时间: 2023-10-15 07:08:14 浏览: 158
好的,下面是一个使用Python实现手写数字图像识别的卷积神经网络的代码示例:
```python
import numpy as np
# 加载MNIST数据集
def load_data():
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
return (train_images, train_labels), (test_images, test_labels)
# 数据预处理
def preprocess_data(train_images, train_labels, test_images, test_labels):
# 将图片数据归一化到[0, 1]之间
train_images = train_images.astype('float32') / 255
test_images = test_images.astype('float32') / 255
# 将标签数据转换成one-hot编码
num_classes = 10
train_labels = np.eye(num_classes)[train_labels]
test_labels = np.eye(num_classes)[test_labels]
# 扩展维度,以符合卷积网络的输入要求
train_images = np.expand_dims(train_images, axis=-1)
test_images = np.expand_dims(test_images, axis=-1)
return train_images, train_labels, test_images, test_labels
# 定义卷积神经网络
def create_model():
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
from keras.models import Model
input_shape = (28, 28, 1)
inputs = Input(shape=input_shape)
# 第一层卷积层
x = Conv2D(filters=32, kernel_size=(3, 3), activation='relu', padding='same')(inputs)
x = MaxPooling2D(pool_size=(2, 2))(x)
# 第二层卷积层
x = Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
# 第三层卷积层
x = Conv2D(filters=128, kernel_size=(3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
# 将卷积层的输出展平
x = Flatten()(x)
# 全连接层
x = Dense(units=128, activation='relu')(x)
x = Dense(units=10, activation='softmax')(x)
model = Model(inputs=inputs, outputs=x)
return model
# 训练模型
def train_model(model, train_images, train_labels, test_images, test_labels):
from keras.callbacks import ModelCheckpoint, EarlyStopping
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 定义训练过程中的回调函数
checkpoint = ModelCheckpoint(filepath='model.h5', monitor='val_accuracy', save_best_only=True, verbose=1)
earlystop = EarlyStopping(monitor='val_accuracy', patience=5, verbose=1)
callbacks = [checkpoint, earlystop]
# 训练模型
model.fit(train_images, train_labels, batch_size=128, epochs=20, validation_data=(test_images, test_labels), callbacks=callbacks)
# 在测试集上评估模型性能
def evaluate_model(model, test_images, test_labels):
loss, accuracy = model.evaluate(test_images, test_labels, verbose=1)
print('Test accuracy:', accuracy)
if __name__ == '__main__':
# 加载数据集
(train_images, train_labels), (test_images, test_labels) = load_data()
# 数据预处理
train_images, train_labels, test_images, test_labels = preprocess_data(train_images, train_labels, test_images, test_labels)
# 创建模型
model = create_model()
# 训练模型
train_model(model, train_images, train_labels, test_images, test_labels)
# 评估模型性能
evaluate_model(model, test_images, test_labels)
```
以上代码使用Keras库来定义卷积神经网络,并使用MNIST数据集来训练和测试模型。注意,由于题目中要求不使用框架,因此上述代码仅提供参考,可能存在一些语法或实现细节上的问题。
阅读全文