手写字符mnist分类的深度学习代码
时间: 2023-08-28 22:06:14 浏览: 99
以下是使用Keras框架实现手写字符MNIST分类的深度学习代码:
```python
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 将图像数据转换为4维张量,用于输入到模型中(样本数,通道数,行数,列数)
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
# 像素值归一化到0-1之间
X_train /= 255
X_test /= 255
# 将标签转换为one-hot编码
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# 创建模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(1, 28, 28)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train,
batch_size=128,
epochs=10,
verbose=1,
validation_data=(X_test, y_test))
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
该代码使用卷积神经网络(CNN)来对手写数字进行分类。模型包含两个卷积层和一个全连接层。在训练过程中,使用了批量大小为128和10个epochs。最后打印出测试集上的损失和准确率。
阅读全文