Python深度学习笔记07--使用Keras建立卷积神经网络

 1 from keras.datasets import mnist
 2 from keras.utils import to_categorical
 3 
 4 #1. 获取数据
 5 (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
 6 
 7 #2. 处理数据
 8 train_images = train_images.reshape((60000, 28, 28, 1))
 9 train_images = train_images.astype('float32') / 255
10 
11 test_images = test_images.reshape((10000, 28, 28, 1))
12 test_images = test_images.astype('float32') / 255
13 
14 train_labels = to_categorical(train_labels)
15 test_labels = to_categorical(test_labels)
16 
17 from keras import layers
18 from keras import models
19 
20 #3. 建立网络模型
21 model = models.Sequential()
22 model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
23 model.add(layers.MaxPooling2D((2, 2)))
24 model.add(layers.Conv2D(64, (3, 3), activation='relu'))
25 model.add(layers.MaxPooling2D((2, 2)))
26 model.add(layers.Conv2D(64, (3, 3), activation='relu'))
27 
28 model.add(layers.Flatten())
29 model.add(layers.Dense(64, activation='relu'))
30 model.add(layers.Dense(10, activation='softmax'))
31 
32 # print(model.summary())
33 
34 '''
35 #网络参数计算方式
36 1.conv2d有320个参数,计算方式:(3 * 3 * 1 + 1) * 32
37 2.conv2d_1有18496个参数,计算方式:(3 * 3 * 32 + 1) * 64
38 3.conv2d_2有36928个参数,计算方式:(3 * 3 * 64 + 1) * 64
39 4.dense有36928个参数,计算方式:(576 + 1) * 64
40 5.dense_1有650个参数,计算方式:(64 + 1) * 10
41 '''
42 #4. 设置编译参数
43 model.compile(optimizer='rmsprop',
44               loss='categorical_crossentropy',
45               metrics=['accuracy'])
46 
47 #5. 设置训练条件并训练             
48 model.fit(train_images, train_labels, epochs=5, batch_size=64)
49 
50 #6. 评估模型
51 test_loss, test_acc = model.evaluate(test_images, test_labels)
52 #313/313 [==============================] - 1s 3ms/step - loss: 0.0324 - accuracy: 0.9898
53 
54 print(test_acc)
55 #0.989799976348877

 

上一篇:BindsNET学习系列——Network


下一篇:网络