减小 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() 将只有嵌入层之后的管道部分。相反,您将使用嵌入的维度在 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)