MNIST分类案例
#%%
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Convolution2D, MaxPooling2D, Flatten
from keras.optimizers import Adam
#%%
# x_train shape: (60000, 28, 28) ndarray
# y_train shape: (60000,)
# x_test shape: (10000, 28, 28)
# y_test shape: (10000,)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#%%
# (60000, 28, 28) -> (60000, 28, 28, 1)
# 归一化
x_train = x_train.reshape(-1, 28, 28, 1) / 255.
x_test = x_test.reshape(-1, 28, 28, 1) / 255.
#%%
# to one-hot
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
#%%
model = Sequential()
# 卷积层
model.add(Convolution2D(
# 输入形状
input_shape=(28, 28, 1),
# 卷积核个数
filters=32,
# 卷积核大小
# 5*5
kernel_size=5,
# 步长
strides=1,
# padding方式 same或valid
# same 得到的平面大小还是28*28
padding='same',
# 激活函数
activation='relu'))
# 池化层 变为14*14
model.add(MaxPooling2D(
pool_size=2,
strides=2,
padding='same'
))
model.add(Convolution2D(filters=64, kernel_size=5, strides=1, padding='same', activation='relu'))
# 变为7*7
model.add(MaxPooling2D(2, 2, 'same'))
# 变为1维
model.add(Flatten())
# 全连接层
model.add(Dense(1024, activation='relu'))
# Dropout
model.add(Dropout(0.5))
# 输出10个类别
model.add(Dense(10, activation='softmax'))
#%%
# 优化器 学习率1e-4
adam = Adam(lr=1e-4)
#%%
# 编译模型
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])
#%%
# 训练
model.fit(x_train, y_train, batch_size=64, epochs=10)
#%%
# 模型评价
loss, accuracy = model.evaluate(x_test, y_test)
#%%
print(loss)
print(accuracy)