Keras外科医生:用于修剪和模型优化

时间:2019-12-04 09:08:24

标签: python optimization keras conv-neural-network pruning

我正在研究使用Keras构建的卷积神经网络。由于最终模型需要部署在处理能力较低的处理单元上,因此我开始寻找减少消耗资源的方法。幸运的是,我在Keras-surgeon的Keras中遇到了这个库,该库有助于修改训练有素的Keras模型。

我正在尝试删除我的Conv Net图层之一中的频道(并将在其他图层上继续进行)。尽管文档非常简单明了,并且使用过它的人也赞扬它,但是当我尝试使用它时,它会返回一个奇怪的类型错误:

from kerassurgeon import Surgeon

surgeon = Surgeon(model_final)
layer_1 = model_final.layers[1] # selecting 2nd layer

surgeon.add_job('delete_channels', layer_1, channels=[4,7,3])
new_model = surgeon.operate()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-292-77c377538a52> in <module>
      5 
      6 surgeon.add_job('delete_channels', layer_1, channels=[4,7,3])
----> 7 new_model = surgeon.operate()

~/anaconda3/envs/Learning/lib/python3.6/site-packages/kerassurgeon/surgeon.py in operate(self)
    150         for node in sorted_nodes:
    151             # Rebuild submodel up to this node
--> 152             sub_output_nodes = utils.get_node_inbound_nodes(node)
    153             outputs, output_masks = self._rebuild_graph(self.model.inputs,
    154                                                         sub_output_nodes)

~/anaconda3/envs/Learning/lib/python3.6/site-packages/kerassurgeon/utils.py in get_node_inbound_nodes(node)
     88 def get_node_inbound_nodes(node):
     89     return [get_inbound_nodes(node.inbound_layers[i])[node_index]
---> 90             for i, node_index in enumerate(node.node_indices)]
     91 
     92 

TypeError: 'int' object is not iterable
  1. 我在这里到底在做什么错?

  2. 还可以有人指出我可以用来运行keras模型的任何东西,以查看其资源消耗(内存和CPU等)吗? (这将是很大的帮助!)

  3. 我可以采用什么其他方法来建立一个在不影响准确性的情况下占用更少资源的模型?

任何帮助将不胜感激..!

3 个答案:

答案 0 :(得分:1)

使用tfkerassurgeon将解决此问题。

pip install tfkerassurgeon

答案 1 :(得分:0)

definition of add_job是:

def add_job(self, job, layer, *,
            channels=None, new_layer=None, node_indices=None):
  # ...

函数参数中的*旨在强制您显式使用命名参数。 您必须按以下方式致电add_job

surgeon.add_job('delete_channels', layer_1, channels=[4,7,3])

答案 2 :(得分:0)

当某些函数需要一个 int(或对象)列表并且我传递一个 int(或对象)时,我看到了这个错误。也许试试 surgeon.add_job('delete_channels', [layer_1], channels=[4,7,3]) 代替 surgeon.add_job('delete_channels', layer_1, channels=[4,7,3])