簡體   English   中英

減小Keras LSTM型號的尺寸

[英]Reduce the size of Keras LSTM model

基本上,我正在使用Keras訓練LSTM模型,但是當我保存它時,它的大小需要100MB。 但是,我的模型的目的是部署到Web服務器以作為API,我的Web服務器無法運行它,因為模型大小太大。 在分析了我的模型中的所有參數后,我發現我的模型有20,000,000參數,但是15,000,000參數是未經訓練的,因為它們是字嵌入。 有沒有什么方法可以通過刪除15,000,000參數來最小化模型的大小,但仍保留模型的性能? 這是我的模型代碼:

def LSTModel(input_shape, word_to_vec_map, word_to_index):


    sentence_indices = Input(input_shape, dtype="int32")

    embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)


    embeddings = embedding_layer(sentence_indices)


    X = LSTM(256, return_sequences=True)(embeddings)
    X = Dropout(0.5)(X)
    X = LSTM(256, return_sequences=False)(X)
    X = Dropout(0.5)(X)    
    X = Dense(NUM_OF_LABELS)(X)
    X = Activation("softmax")(X)

    model = Model(inputs=sentence_indices, outputs=X)

    return model

定義要在函數外部保存的圖層並命名它們。 然后創建兩個函數foo()bar() foo()將擁有包含嵌入層的原始管道。 bar()將只包含管道AFTER嵌入層的一部分。 相反,您將在bar()具有嵌入尺寸的新Input()圖層:

lstm1 = LSTM(256, return_sequences=True, name='lstm1')
lstm2 = LSTM(256, return_sequences=False, name='lstm2')
dense = Dense(NUM_OF_LABELS, name='Susie Dense')

def foo(...):
    sentence_indices = Input(input_shape, dtype="int32")
    embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)
    embeddings = embedding_layer(sentence_indices)
    X = lstm1(embeddings)
    X = Dropout(0.5)(X)
    X = lstm2(X)
    X = Dropout(0.5)(X)    
    X = dense(X)
    X = Activation("softmax")(X)
    return Model(inputs=sentence_indices, outputs=X)


def bar(...):
    embeddings = Input(embedding_shape, dtype="float32")
    X = lstm1(embeddings)
    X = Dropout(0.5)(X)
    X = lstm2(X)
    X = Dropout(0.5)(X)    
    X = dense(X)
    X = Activation("softmax")(X)
    return Model(inputs=sentence_indices, outputs=X)

foo_model = foo(...)
bar_model = bar(...)

foo_model.fit(...)
bar_model.save_weights(...)

現在,您將訓練原始的foo()模型。 然后,您可以保存縮小的bar()模型的權重。 加載模型時,不要忘記指定by_name=True參數:

foo_model.load_weights('bar_model.h5', by_name=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM