本质上,我正在使用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)