#用keras搭建,如下的卷积网络
####本文使用keras,搭建卷积模型
1 import numpy as np
2 import tensorflow as tensorflow
3
4 from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
5 from keras.layers import Dropout, Flatten, Dense
6 from keras.models import Sequential
7
8 #初始化一个模型
9 model = Sequential()
10
11 ### TODO: 定义你的网络架构
12 #卷积层1
13 model.add(Conv2D(filters=16,kernel_size=(3,3),strides=(1,1),padding="same"
14 ,input_shape=(224,224,3),activation="relu"))
15 #最大池化1
16 model.add(MaxPooling2D(pool_size=(2,2)))
17 #丢弃
18 model.add(Dropout(0.5))
19
20 #卷积层2
21 model.add(Conv2D(filters=32,kernel_size=(3,3),strides=(1,1),padding="same"
22 ,activation="relu"))
23 #最大池化2
24 model.add(MaxPooling2D(pool_size=(2,2)))
25 #丢弃
26 model.add(Dropout(0.5))
27
28 #卷积层3
29 model.add(Conv2D(filters=64,kernel_size=(3,3),strides=(1,1),padding="same"
30 ,activation="relu"))
31
32 #最大池化3
33 model.add(MaxPooling2D(pool_size=(2,2)))
34 #丢弃
35 model.add(Dropout(0.5))
36
37 #扁平化,用全区平均池化代替
38 # model.add(Flatten())
39
40 #全局平均池化
41 model.add(GlobalAveragePooling2D())
42 #一个全连接层,共133个分类,激活函数使用"softmax"
43 model.add(Dense(133, activation="softmax"))
44
45 ## 编译模型
46 model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
47
48 #显示模型结构
49 model.summary()
50
51
52
53 #########################################
54 ##训练模型
55 from keras.callbacks import ModelCheckpoint
56
57 ### TODO: 设置训练模型的epochs的数量
58
59 epochs = 5
60
61 ### 不要修改下方代码
62
63 checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5',
64 verbose=1, save_best_only=True)
65
66 model.fit(train_tensors, train_targets,
67 validation_data=(valid_tensors, valid_targets),
68 epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
69
70
71
72 ################################################
73
74 ## 加载具有最好验证loss的模型
75 model.load_weights('saved_models/weights.best.from_scratch.hdf5')
76
77
78
79 ##################################################
80
81 # 获取测试数据集中每一个图像所预测的狗品种的index
82 dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]
83
84 # 报告测试准确率
85 test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
86 print('Test accuracy: %.4f%%' % test_accuracy)