Keras操作小技巧(持續更新ing)

Keras是用Python編寫的高級神經網絡API,能夠在TensorFlow,CNTK或Theano之上運行。它的開發着眼於實現快速實驗。這篇博客主要記錄博主在Keras操作中遇到的一些簡單快速的小技巧,夥伴們可以按需閱讀(具體的操作可以參見目錄⬆️,目錄之間沒有什麼聯繫,就是遇到了隨手記下來)~如果想了解更多關於Keras的問題,可以參見Keras官方文檔
在這裏插入圖片描述

Part00 指定使用服務器的卡:os.environ

這個嚴格意義上不算是Keras的範圍內,但是順手也記錄在了這裏,按需自取。

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"

Part01 分類網絡預測時如何設置Top-5:Keras.Metircs

我們以AlexNet爲例,一般用accuracy做爲metrics來約束loss,但有時我們也需要用top-5來看預測的類是否進入前五名,尤其是在分類難度比較大,類別比較多的時候。在官方文檔Metrics中還有很多其他的metrics的設置,可以參考。

import keras

def acc_top5(y_true, y_pred):
	return keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=5)

def train(aug,trainX,trainY,testX,testY):
	print("[INFO] compiling model...")
	model = Alexnet.build(width=norm_size, height=norm_size, depth=1, classes=CLASS_NUM)
	opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
	model.compile(loss="sparse_categorical_crossentropy", optimizer=opt, metrics=["accuracy", acc_top5])

Part02 在訓練過程中存儲最好的權重模型:ModelCheckpoint

在網絡訓練過程中,假設epoch=20,但是並不一定在第20個epoch的時候驗證集的效果是最好的,有可能優化出現了波動也有可能會過擬合,所以除去存儲最後一輪訓練的權重模型以外,還要存儲在訓練過程中驗證集表現最好的模型,還是以Alexnet爲例。

import keras
from keras.callbacks import ModelCheckpoint

def train(aug,trainX,trainY,testX,testY):
	print("[INFO] compiling model...")
	model = Alexnet.build(width=norm_size, height=norm_size, depth=1, classes=CLASS_NUM)
	opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
	model.compile(loss="sparse_categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
	
	checkpoint = ModelCheckpoint(filepath='alexnet_best.h5',monitor='val_acc',mode='auto' ,save_best_only='True')
    callback_lists=[checkpoint]
    
    H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS),
        validation_data=(testX, testY), steps_per_epoch=len(trainX) // BS,
        epochs=EPOCHS, verbose=1, callbacks=callback_lists)
    
    model.save('alexnet.h5')
    print("[INFO] save network finished")

Part03 快速數據擴增數據集:ImageDataGenerator

在Keras中也有很好用的快速數據擴增的辦法,在官方文檔Image Preprocessing中小夥伴們可以找到各種參數,根據自己的需求調用參數就可以了。舉個例子:

aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1,
                         height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,
                         horizontal_flip=True, fill_mode="nearest")

Part04 打印模型的參數和計算參數量:print_summary()

我們在上述問題中已經解決了如何存儲模型和根據驗證集的準確率存儲優秀的模型model.save('xxx.h5),那麼如何來打印模型的各層參數和計算整個的參數量呢?其實在Keras裏非常方便(因爲有model.suquential),用Convnet來舉個例子:如果你沒有現成的已經存儲好的模型,那麼你可以⬇️:

import keras
from keras.models import Sequential, Model
from keras.layers import Input, add
from keras.layers.convolutional import MaxPooling2D, AveragePooling2D, ZeroPadding2D, Conv2D
from keras.layers.core import Activation, Flatten, Dense, Dropout 
from keras.layers.normalization import BatchNormalization
from keras import backend as K
from keras.utils import print_summary

# Define a network
class Convnet:
    @staticmethod
    def build(width, height, depth, classes):
        model = Sequential()
        inputShape = (height, width, depth)
        if K.image_data_format() == "channels_first":  
            inputShape = (depth, height, width)
        
        model.add(Conv2D(64, (5, 5),padding="same",input_shape=inputShape))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2,2)))
        model.add(BatchNormalization())
        model.add(Conv2D(256, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
        model.add(BatchNormalization())
        model.add(Flatten())
        model.add(Dense(1000))
        model.add(Activation("relu"))
        model.add(Dropout(0.5))
        model.add(Dense(classes))
        model.add(Activation("softmax"))
        return model 

# Define model
model = Convnet.build(width=28, height=28, depth=1, classes=3755) # Input size and catogries
print_summary(model, line_length=None, positions=None, print_fn=None)

然後運行,你就可以得到如下的結果圖了:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章