# 周末AI课堂：卷积之上的新操作 代码篇

AI课堂开讲，就差你了！

from keras.layers import Conv2D

Conv2D(filters=32,kernel_size=(3,3),strides=(1,1),\

from keras.layers import

from keras.layers import Input

from keras.models import Model

from keras.layers import Dense,Activation,Flatten

from keras.layers import BatchNormalization as BN

def Dense_bn(x,units):

x = Dense(units)(x)

x =BN()(x)

x =Activation('relu')(x)

return x

from keras.layers import Conv2D,MaxPooling2D

def normal_model():

x= Input(shape=(28*28,))

x2= Dense_bn(x,1000)

x3=Dense_bn(x2,512)

x4=Dense_bn(x3,256)

y=Dense(10,activation='softmax')(x4)

model = Model(inputs=x, outputs=y)

model.compile(optimizer='SGD',\

loss='categorical_crossentropy',\

metrics=['accuracy'])

return(model)

Total params: 1,438,482

Trainable params: 1,434,946

Non-trainable params: 3,536

def Conv2D_bn(x,filters,length,width,\

x = Conv2D(filters, (length, width),\

x = BN()(x)

x = Activation('relu')(x)

return x

def conv_model():

x= Input(shape=(28,28,1))

x2= Conv2D_bn(x,64,3,3)

x3= Conv2D_bn(x2,32,3,3)

x4=Flatten()(x3)

x5=Dense_bn(x4,32)

y=Dense(10,activation='softmax')(x5)

model = Model(inputs=x, outputs=y）

model.compile(optimizer='SGD',\

loss='categorical_crossentropy',\

metrics=['accuracy'])

return(model)

Total params: 822,794

Trainable params: 822,538

Non-trainable params: 256

import matplotlib.pyplot as plt

import seaborn as sns

model_1=normal_model()

his1=model_1.fit(X_train_normal,train_labels,\

batch_size=128,validation_split=0.3,\

verbose=1,epochs=10)

model_2=conv_model()

his2=model_2.fit(X_train_conv,train_labels,batch_size=128,\ validation_split=0.3,verbose=1,\

epochs=10)

w2=his2.history

w1=his1.history

sns.set(style='whitegrid')

plt.plot(range(10),w1['acc'],'b-.',label='Normal train')

plt.plot(range(10),w2['acc'],'r-.',label='CNN train')

plt.plot(range(10),w1['val_acc'],'b-',label='Normal test')

plt.plot(range(10),w2['val_acc'],'r-',label='CNN test')

plt.xlabel('epochs')

plt.ylabel('accuracy')

plt.legend()plt.show()

def conv_model_pooling():

x= Input(shape=(28,28,1))

x2= Conv2D_bn(x,64,3,3)

x3=MaxPooling2D(2)(x2)

x4= Conv2D_bn(x3,32,3,3)

x5=Flatten()(x4)

x6=Dense_bn(x5,32)

y=Dense(10,activation='softmax')(x6)

model = Model(inputs=x, outputs=y)

model.compile(optimizer='SGD',loss='categorical_crossentropy',\

metrics=['accuracy'])

return(model)

Total params: 220,682

Trainable params: 220,426

Non-trainable params: 256

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20181209A13WBP00?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2021-11-29

2021-11-29

2021-11-29

2021-11-29

2021-11-29

2021-11-29

2018-06-14

2018-05-11

2021-11-29

2021-11-29

2021-11-29

2021-11-29