使用keras,手動搭建卷積模型
阿新 • • 發佈:2018-07-30
卷積 color compile flatten point span 結構 shape 圖像
####本文使用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)
使用keras,手動搭建卷積模型