【问题标题】:how to calculate a net's FLOPs in CNN [closed]如何在 CNN 中计算网络的 FLOPs [关闭]
【发布时间】:2017-09-15 09:03:58
【问题描述】:

我想设计一个占用GPU资源不超过Alexnet的卷积神经网络。我想用FLOPs来测量它但我不知道如何计算它。请问有什么工具可以做到吗?

【问题讨论】:

标签: neural-network deep-learning caffe conv-neural-network


【解决方案1】:

有关在线工具,请参阅http://dgschwend.github.io/netscope/#/editor。对于 alexnet,请参阅 http://dgschwend.github.io/netscope/#/preset/alexnet 。这支持最广为人知的层。对于自定义图层,您必须自己计算。

【讨论】:

【解决方案2】:

对于未来的访问者,如果您使用 Keras 和 TensorFlow 作为后端,那么您可以尝试以下示例。它计算 MobileNet 的 FLOP。

import tensorflow as tf
import keras.backend as K
from keras.applications.mobilenet import MobileNet

run_meta = tf.RunMetadata()
with tf.Session(graph=tf.Graph()) as sess:
    K.set_session(sess)
    net = MobileNet(alpha=.75, input_tensor=tf.placeholder('float32', shape=(1,32,32,3)))

    opts = tf.profiler.ProfileOptionBuilder.float_operation()    
    flops = tf.profiler.profile(sess.graph, run_meta=run_meta, cmd='op', options=opts)

    opts = tf.profiler.ProfileOptionBuilder.trainable_variables_parameter()    
    params = tf.profiler.profile(sess.graph, run_meta=run_meta, cmd='op', options=opts)

    print("{:,} --- {:,}".format(flops.total_float_ops, params.total_parameters))

【讨论】:

【解决方案3】:

如果您使用的是 Keras,则可以在此拉取请求中使用补丁:https://github.com/fchollet/keras/pull/6203

然后只需调用 print_summary(),您就会看到每层的失败次数和总数。

即使不使用 Keras,也值得在 Keras 中重新创建您的网络,这样您就可以获得失败次数。

【讨论】:

    【解决方案4】:

    如果您使用的是 TensorFlow v1.x,Tobias Scheck 的答案有效,但如果您使用的是 TensorFlow v2.x,则可以使用以下代码:

    import tensorflow as tf
    
    def get_flops(model_h5_path):
        session = tf.compat.v1.Session()
        graph = tf.compat.v1.get_default_graph()
            
    
        with graph.as_default():
            with session.as_default():
                model = tf.keras.models.load_model(model_h5_path)
    
                run_meta = tf.compat.v1.RunMetadata()
                opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation()
            
                # We use the Keras session graph in the call to the profiler.
                flops = tf.compat.v1.profiler.profile(graph=graph,
                                                      run_meta=run_meta, cmd='op', options=opts)
            
                return flops.total_float_ops
    

    上述函数采用h5格式保存模型的路径。您可以通过以下方式保存模型并使用该功能:

    model.save('path_to_my_model.h5')
    tf.compat.v1.reset_default_graph()
    print(get_flops('path_to_my_model.h5'))
    

    请注意,我们使用tf.compat.v1.reset_default_graph() 来避免每次调用函数时累积 FLOPS。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多