手写数字识别
MNIST数据集用于评估手写数字分类问题的数据集。
import tensorflow
import keras
from keras.datasets import mnist
from matplotlib import pyplot as plt
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
#从Keras导入mnist数据集
(X_train,y_train),(X_validation,y_validation) = mnist.load_data()
#显示4张手写数字图片
#一个Figure对象可以包含多个子图,可以使用subplot()快速绘制.
#其调用形式为subplot(行号,列号,图号)
plt.subplot(221)
plt.imshow(X_train[0],cmap=plt.get_cmap('gray'))
plt.subplot(222)
plt.imshow(X_train[1],cmap=plt.get_cmap('gray'))
plt.subplot(223)
plt.imshow(X_train[2],cmap=plt.get_cmap('gray'))
plt.subplot(224)
plt.imshow(X_train[3],cmap=plt.get_cmap('gray'))
plt.show()
输入层(784个输入)隐藏层(784个神经元)输出层(10个神经元)
import tensorflow
import keras
from keras.datasets import mnist
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
import numpy as np
#从Keras导入MNIST数据集
(X_train,y_train),(X_validation,y_validation) = mnist.load_data()
#设定随机数种子
seed = 7
np.random.seed(seed)
#显示4张手写数字图片
plt.subplot(221)
plt.imshow(X_train[0],cmap=plt.get_cmap('gray'))
plt.subplot(222)
plt.imshow(X_train[1],cmap=plt.get_cmap('gray'))
plt.subplot(223)
plt.imshow(X_train[2],cmap=plt.get_cmap('gray'))
plt.subplot(224)
plt.imshow(X_train[3],cmap=plt.get_cmap('gray'))
plt.show()
num_pixels = X_train.shape[1]*X_train.shape[2]
print(num_pixels)
X_train = X_train.reshape(X_train.shape[0],num_pixels).astype('float32')
x_validation = X_validation.reshape(X_validation.shape[0],num_pixels).astype('float32')
#格式化数据0-1
X_train = X_train/255
X_validation = X_validation/255
#进行one-hot编码
y_train = np_utils.to_categorical(y_train)
y_validation = np_utils.to_categorical(y_validation)
num_classes = y_validation.shape[1]
print(num_classes)
#创建基准MLP模型
def create_model():
#创建模型
model = Sequential()
model.add(Dense(input_dim=num_pixels,units=num_pixels,activation='relu',kernel_initializer='normal'))
model.add(Dense(units=num_classes,kernel_initializer='normal',activation='softmax'))
#编译模型
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']
return model
model = create_model()
model.fit(batch_size=200,epochs=10,x=X_train,y=y_train)
score = model.evaluate(x=X_validation,y=y_validation)
print('MLP:%.2f%%' %(score[1]*100))
Keras提供了可以很简单地创建卷积神经网络地API。
演示如何在Keras中实现卷积神经网络,包括卷积层、池化层和全连接层。
import tensorflow
import keras
from keras.datasets import mnist
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend
backend.set_image_data_format('channels_first')
#设定随机数种子
seed = 7
np.random.seed(seed)
#从Keras导入MNIST数据集
(X_train,y_train),(X_validation,y_validation) = mnist.load_data()
X_train = X_train.reshape(X_train.shape[0],1,28,28).astype('float32')
X_validation = X_validation.reshape(X_validation.shape[0],1,28,28).astype('float32')
#格式化数据0-1
X_train = X_train / 255
X_validation = X_validation / 255
#进行one-hot编码
y_train = np_utils.to_categorical(y_train)
y_validation = np_utils.to_categorical(y_validation)
#创建模型
def create_model():
model = Sequential()
model.add(Conv2D(32,(5,5),input_shape=(1,28,28),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(units=128,activation='relu'))
model.add(Dense(units=10,activation='softmax'))
#编译模型
model.compile(loss='categorical_crossentropy',optimizer = 'adam',metrics = ['accuracy'])
return model
model = create_model()
model.fit(X_train,y_train,epochs = 10,batch_size = 200,verbose = 2)
score = model.evaluate(X_validation,y_validation,verbose = 0)
print('CNN_Small:%.2f%%' %(score[1]*100))
复杂卷积神经网络
在卷积神经网络中可以有多个卷积层。网络拓扑结构如下:
只有模型层发生变化
#创建模型
def create_model():
model = Sequential()
model.add(Conv2D(32,(5,5),input_shape=(1,28,28),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(15,(3,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(units=128,activation='relu'))
model.add(Dense(units=50,activation='relu'))
model.add(Dense(units=10,activation='softmax'))
#编译模型
model.compile(loss='categorical_crossentropy',optimizer = 'adam',metrics = ['accuracy'])
return model
从结果可以看出,识别准确度有一定程度的提升。