pytorch和tensorflow计算Flops和params

1.只计算params

    net = model()  # 定义好的网络模型
    total = sum([param.nelement() for param in net.parameters()])
    print("Number of parameter: %.2fM" % total)

这是网上很常见的直接用自带方法计算params,基本不会出错。胜在简洁。

2.计算flops和params

要计算flops,目前没见到用自带方法计算的,基本都是要安装别的库。
这边我们安装thop库。

pip install thop # 安装thop库
import torch
from thop import profile
net = model()  # 定义好的网络模型
img1 = torch.randn(1, 3, 512, 512)
img2 = torch.randn(1, 3, 512, 512)
img3 = torch.randn(1, 3, 512, 512)
macs, params = profile(net, (img1,img2,img3))
print('flops: ', 2*macs, 'params: ', params)

这边和其他网上教程的区别便是,他们macs和flops不分。因为macs表示乘加累积操作数一个乘法加上一个加法才算一个macs。而flops表示浮点运算次数,每一个加、减、乘、除操作都算1FLOPs操作。所以很明显,在数值上,1flops=2macs。此外,(img1,img2,img3)就表示你如果有三个输入要输入模型,就这样写

import torch
from torchvision.models import resnet50
from fvcore.nn import FlopCountAnalysis, parameter_count_table

# 创建resnet50网络
model = resnet50(num_classes=1000)

# 创建输入网络的tensor
tensor = (torch.rand(1, 3, 224, 224),)

# 分析FLOPs
flops = FlopCountAnalysis(model, tensor)
print("FLOPs: ", flops.total())
print(parameter_count_table(generator))

另外,要注意,params只和模型参数量相关,而和输入tensor大小无关。但flops和输入图片大小是相关的.

3.tensorflow计算params和flops

此处是我找到的一些用于tensorflow计算params和flops的方法,仅供参考,不保证效果。

def get_flops_params():
    sess = tf.compat.v1.Session()
    graph = sess.graph
    flops = tf.compat.v1.profiler.profile(graph, options=tf.compat.v1.profiler.ProfileOptionBuilder.float_operation())
    params = tf.compat.v1.profiler.profile(graph,
                                           options=tf.compat.v1.profiler.ProfileOptionBuilder.trainable_variables_parameter())
    print('FLOPs: {};    Trainable params: {}'.format(flops.total_float_ops, params.total_parameters))


def count2():
    print(np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]))


def get_nb_params_shape(shape):
    '''
    Computes the total number of params for a given shap.
    Works for any number of shapes etc [D,F] or [W,H,C] computes D*F and W*H*C.
    '''
    nb_params = 1
    for dim in shape:
        nb_params = nb_params * int(dim)
    return nb_params


def count3():
    tot_nb_params = 0
    for trainable_variable in tf.trainable_variables():
        shape = trainable_variable.get_shape()  # e.g [D,F] or [W,H,C]
        current_nb_params = get_nb_params_shape(shape)
        tot_nb_params = tot_nb_params + current_nb_params
    print(tot_nb_params)




import tensorflow.compat.v1 as tf
tf.compat.v1.disable_eager_execution()
from model import Model

import keras.backend as K


def get_flops(model):
    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 ....
M = Model(BATCH_SIZE=1, INPUT_H=268, INPUT_W=360, is_training=False)
print(get_flops(M))

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值