如何在 CNN 中计算网络的 FLOPs

how to calculate a net's FLOPs in CNN

我想设计一个占用GPU资源不超过Alexnet.I的卷积神经网络想用FLOPs来衡量但不知道怎么计算it.Is有什么工具可以做吧,好吗?

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

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

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

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

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

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))

如果您使用的是 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。