deep-learning - 如何在 Keras 中计算 Mobilenet FLOPs

标签 deep-learning keras flops

run_meta = tf.RunMetadata()
enter codwith tf.Session(graph=tf.Graph()) as sess:
K.set_session(sess)


with tf.device('/cpu:0'):
    base_model = MobileNet(alpha=1, weights=None, input_tensor=tf.placeholder('float32', shape=(1,224,224,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))

当我运行上面的代码时,我得到了下面的结果

1,137,481,704 --- 4,253,864

这与论文中描述的触发器不同。

手机网:https://arxiv.org/pdf/1704.04861.pdf

ShuffleNet:https://arxiv.org/pdf/1707.01083.pdf

如何计算论文中描述的精确触发器?

最佳答案

tl;博士 你真的得到了正确的答案!您只是将触发器与乘法累加(来自论文)进行比较,因此需要除以二。
如果您使用的是 Keras,那么您列出的代码有点过于复杂了……
model是任何编译的 Keras 模型。我们可以使用以下代码得出模型的失败点。

import tensorflow as tf
import keras.backend as K


def get_flops():
    run_meta = tf.RunMetadata()
    opts = tf.profiler.ProfileOptionBuilder.float_operation()

    # We use the Keras session graph in the call to the profiler.
    flops = tf.profiler.profile(graph=K.get_session().graph,
                                run_meta=run_meta, cmd='op', options=opts)

    return flops.total_float_ops  # Prints the "flops" of the model.


# .... Define your model here ....
# You need to have compiled your model before calling this.
print(get_flops())
但是,当我查看自己在计算机上所做的示例(不是 Mobilenet)时,打印出来的 total_float_ops 是 2115 当我简单地打印 flops 时,我得到了以下结果多变的:
[...]
Mul                      1.06k float_ops (100.00%, 49.98%)
Add                      1.06k float_ops (50.02%, 49.93%)
Sub                          2 float_ops (0.09%, 0.09%)
很明显total_float_ops属性考虑乘法、加法和减法。
然后我回顾了 MobileNets 的例子,简单地翻阅了论文,我发现 MobileNet 的实现是基于参数数量的默认 Keras 实现:
image
表中的第一个模型与您的结果 (4,253,864) 相匹配,并且多加值大约是 flops 的一半结果你有。因此,您有正确的答案,只是您将翻牌误认为是乘法加法(又名乘法累加或 MAC)。
如果您想计算 MAC 的数量,您只需将上述代码的结果除以 2。

重要提示
如果您尝试运行代码示例,请记住以下几点:
  • 代码示例 写于 2018 年,不适用于 tensorflow 版本 2。有关 tensorflow 版本 2 兼容性的完整示例,请参阅 @driedler 的答案。
  • 代码示例 最初打算在编译模型上运行一次......有关以没有副作用的方式使用它的更好示例(因此可以在同一模型上多次运行),请参阅@ch271828n 的答案.
  • 关于deep-learning - 如何在 Keras 中计算 Mobilenet FLOPs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525776/

    相关文章:

    c - 处理器的 Gigaflops

    performance - 什么是 FLOP/s?它是衡量性能的一个很好的指标吗?

    python - 如何在python中以随机角度旋转3D图像

    python - PyTorch - normal() 初始化对梯度的影响

    python - Tensorflow:AttributeError: 'function' 对象没有属性 'graph'

    python - keras多层LSTM模型的股价预测收敛于恒定值

    python - 只训练一些词嵌入(Keras)

    c# - 如何测量我的 C# 应用程序使用的 FLOPS?

    machine-learning - Caffe 损失层、均值和准确度

    machine-learning - Caffe 或卷积网络中的批量大小是多少