Keras教程
作者: 时海
识别手写数字--CNN

使用CNN模型训练识别手写数字:


# -*- coding: UTF-8 -*-
import numpy as np
from keras.datasets import mnist
from keras.layers import Dense, Conv2D, MaxPool2D, Dropout, Flatten
from keras.models import Sequential, load_model
from keras.utils import np_utils

# 加载数据
local_path = '/home/mnist.npz'
(x_train, y_train), (x_test, y_test) = mnist.load_data(path=local_path);
print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)
# (60000, 28, 28) (60000,) (10000, 28, 28) (10000,)

# 数据格式转换
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255
print(x_train.shape)
print(x_test.shape)
# (60000, 1, 28, 28)
# (10000, 1, 28, 28)


# 转换成one-hot
y_train_new = np_utils.to_categorical(y_train)
y_test_new = np_utils.to_categorical(y_test)

print(y_train.shape)
print(y_test.shape)


# (60000, 10)
# (10000, 10)


def train():
    # 构造模型
    model = Sequential()
    model.add(Conv2D(32, (5, 5), input_shape=(28, 28, 1), activation='relu'))
    model.add(MaxPool2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(10, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())

    # 训练模型
    model.fit(x_train, y_train_new, epochs=10, batch_size=50)

    # 模型评估
    score = model.evaluate(x_test, y_test_new)
    print(score)
    # [0.039317459321332626, 0.9894000291824341]

    model.save("../data/mnist-cnn.h5")


def predict():
    model = load_model("../data/mnist-cnn.h5")
    y = model.predict(x_test[:5])
    print("predict=>", np.argmax(y, axis=1))
    print("real=>", y_test[:5])
    # predict = > [7 2 1 0 4]
    # real = > [7 2 1 0 4]


train()
predict()



一个创业中的苦逼程序员
  • 回复
隐藏