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 实现:
表中的第一个模型与您的结果 (4,253,864) 相匹配,并且多加值大约是
flops
的一半结果你有。因此,您有正确的答案,只是您将翻牌误认为是乘法加法(又名乘法累加或 MAC)。如果您想计算 MAC 的数量,您只需将上述代码的结果除以 2。
重要提示
如果您尝试运行代码示例,请记住以下几点:
关于deep-learning - 如何在 Keras 中计算 Mobilenet FLOPs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525776/