在函数模型中,我们必须创建一个输入层,用来指定输入数据的形状。输入层采用shape元素(元组)指定输入数据的维度。当输入数据是一维(例如对于多层感知器)时,必须为小批量训练数据留出空间,这是在训练网络时进行数据分割时就确定的,当输入是一维时,shape元组总是由最后一个开放维度来定义。
1、导入模块
from keras.layers import Flatten
from keras.datasets import mnist
import keras
from keras.utils import plot_model # 保存模型图片
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import Reshape
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
2、设置参数、加载数据集(utils.to_categorical对标签进行one_编码)
batch_size = 128
num_classs = 10
epochs = 12
img_rows,img_cols = 28,28
(x_train,y_train),(x_test,y_test) = mnist.load_data()
y_train = keras.utils.to_categorical(y_train,num_classs)
y_test = keras.utils.to_categorical(y_test,num_classs)
3、模型输入
input_shape = (28,28)
inputs = Input(input_shape)
print(input_shape+(1,))
# (28, 28, 1)
x = Reshape(input_shape+(1,),input_shape=input_shape)(inputs)
print(x.shape)
print(type(x))
(28, 28, 1)
(?, 28, 28, 1)
<class 'tensorflow.python.framework.ops.Tensor'>
4、CNN模型创建
x = Reshape(input_shape+(1,),input_shape=input_shape)(inputs)
print(x.shape)
print(type(x))
conv1 = Conv2D(14,kernel_size=4,activation='relu')(x)
pool1 = MaxPooling2D(pool_size=(2,2))(conv1)
conv2 = Conv2D(7,kernel_size=4,activation='relu')(pool1)
pool2 = MaxPooling2D(pool_size=(2,2))(conv2)
flatten = Flatten()(pool2)
output = Dense(10,activation='softmax')(flatten)
model = Model(inputs=inputs,outputs=output)
print(model.summary())
plot_model(model,to_file='cnn_mnist.png')
opt = keras.optimizers.rmsprop(lr=0.0001,decay=1e-6)
model.compile(
loss='categorical_crossentropy',
optimizer=opt,
metrics=['accuracy']
)
model.fit(x_train,y_train,batch_size=batch_size,epochs=epochs
,validation_data = (x_test,y_test),shuffle=True)
score = model.evaluate(x_test,y_test,verbose=1)
print('Test Loss:',score[0])
print('Test Acc:',score[1])
测试结果:
Test Loss: 9.781044848632812
Test Acc: 0.3865
5、调参处理
将第二个卷积层的padding改为same
conv1 = Conv2D(14,kernel_size=4,activation='relu')(x)
pool1 = MaxPooling2D(pool_size=(2,2))(conv1)
conv2 = Conv2D(7,kernel_size=4,padding='same',activation='relu')(pool1)
pool2 = MaxPooling2D(pool_size=(2,2))(conv2)
Test Loss: 0.11397315245843492
Test Acc: 0.9667
将第一个卷积层的padding改为same
conv1 = Conv2D(14,kernel_size=4,padding='same',activation='relu')(x)
pool1 = MaxPooling2D(pool_size=(2,2))(conv1)
conv2 = Conv2D(7,kernel_size=4,activation='relu')(pool1)
pool2 = MaxPooling2D(pool_size=(2,2))(conv2)
Test Loss: 0.1891961853676359
Test Acc: 0.9533
将2个CNN的卷积padding方式都改为same
conv1 = Conv2D(14,kernel_size=4,padding='same',activation='relu')(x)
pool1 = MaxPooling2D(pool_size=(2,2))(conv1)
conv2 = Conv2D(7,kernel_size=4,padding='same',activation='relu')(pool1)
pool2 = MaxPooling2D(pool_size=(2,2))(conv2)
Test Loss: 0.2683791306500323
Test Acc: 0.9343
网友评论