知道了CNN的原理,同样是只要将之前用tensorflow写的几个建立网络的函数用keras的更简单的方法替换就行。
训练结果:
用Sequential().add()添加想要的层,添加卷积层就用Convolution2D(),
例如:卷积核的数量为32,大小5x5,padding为same,输入是一通道,28行28列的图像。
model =Sequential()model.add(Convolution2D(filters=32,kernel_size=5,padding='same',input_shape=(1,28,28)))
总代码:
import numpy as npnp.random.seed(1337)from keras.datasets import mnistfrom keras.utils import np_utilsfrom keras.models import Sequentialfrom keras.layers import Dense,Activation,Convolution2D,MaxPool2D,Flattenfrom keras.optimizers import adam_v2import osos.environ["CUDA_VISIBLE_DEVICES"] = "0"(X_train,y_train),(X_test,y_test) = mnist.load_data()X_train=X_train.reshape(-1,1,28,28)X_test = X_test.reshape(-1,1,28,28)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(filters=32,kernel_size=5,padding='same',input_shape=(1,28,28)))model.add(Activation('relu'))model.add(MaxPool2D(pool_size=(2, 2),strides= (2, 2),padding='same',))model.add(Convolution2D(filters=64,kernel_size=5,padding='same'))model.add(Activation('relu'))model.add(MaxPool2D(pool_size=(2,2),padding='same'))model.add(Flatten())model.add(Dense(1024))model.add(Activation('relu'))model.add(Dense(10))model.add(Activation('softmax'))adam = adam_v2.Adam(learning_rate=1e-4)pile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy'])print('Training---------')model.fit(X_train,y_train,epochs=1,batch_size=32)print('\nTesting---------')loss,accuracy=model.evaluate(X_test,y_test)print('\ntest loss',loss)print('\ntest accuracy',accuracy)