1 import keras 2 from keras.models import Sequential 3 from keras.layers import Input,Dense,Activation,Conv2D,MaxPooling2D,Flatten 4 from keras.datasets import mnist 5 6 7 (x_train,y_train),(x_test,y_test) = mnist.load_data() 8 x_train = x_train.reshape(-1, 28, 28, 1) ####### 9 x_train = x_train.astype("float32") 10 print(x_train.shape) 11 y_train = y_train.astype("float32") 12 x_test = x_test.reshape(-1,28,28,1) 13 x_test = x_test.astype("float32") 14 y_test = y_test.astype("float32") 15 16 print(y_train) 17 x_train /= 255 18 x_test /= 255 19 20 from keras.utils import np_utils 21 y_train_new = np_utils.to_categorical(num_classes=10,y=y_train) 22 print(y_train_new) 23 y_test_new = np_utils.to_categorical(num_classes=10,y=y_test) 24 25 def LeNet_5(): 26 model = Sequential() 27 model.add(Conv2D(filters=6,kernel_size=(5,5),padding="valid",activation="tanh",input_shape=[28, 28, 1])) 28 model.add(MaxPooling2D(pool_size=(2,2))) 29 model.add(Conv2D(filters=16,kernel_size=(5,5),padding="valid",activation="tanh")) 30 model.add(MaxPooling2D(pool_size=(2,2))) 31 model.add(Flatten()) 32 model.add(Dense(120,activation="tanh")) 33 model.add(Dense(84,activation="tanh")) 34 model.add(Dense(10,activation="softmax")) 35 return model 36 37 def train_model(): 38 model = LeNet_5() 39 model.compile(optimizer="adam",loss="categorical_crossentropy",metrics=["accuracy"]) 40 model.fit(x_train,y_train_new,batch_size=64,epochs=1,verbose=1,validation_split=0.2,shuffle=True) 41 return model 42 43 model = train_model() 44 45 loss,accuracy = model.evaluate(x_test,y_test_new) 46 print(loss,accuracy)
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:LeNet-5模型的keras实现 - Python技术站