计算parameters和FLOPs

1. 安装 ptflops

pip install ptflops

2. 计算params和FLOPs

from ptflops import get_model_complexity_info

def print_time_paramter_complexity(net, input_size):
    macs, params = get_model_complexity_info(net, input_size, as_strings=True, print_per_layer_stat=True, verbose=True)
    
    print('{:<30}  {:<8}'.format('Computational complexity: ', macs))
    print('{:<30}  {:<8}'.format('Number of parameters: ', params))

3. 多输入的params和FLOPs

class Model(nn.Module):
	def __init__(self):
		super.__init__()
	
	def forward(self, xs):
		x1, x2 = xs[0], xs[1]
		return x1 + x2

def prepare_input(resolution, input_size):
	"""
		input_size: including batch_size. 
		For threeD, input_size = [(2, 3, 80, 192, 160), (2, 1, 80, 192, 160)]
	"""
    x1 = torch.FloatTensor(input_size[0])
    x2 = torch.FloatTensor(input_size[1])

    return dict(x=(x1, x2))

def print_time_paramter_complexity(net, input_size):
    macs, params = get_model_complexity_info(net, input_size, as_strings=True, print_per_layer_stat=True, verbose=True,
    input_constructor=prepare_input)

    print('{:<30}  {:<8}'.format('Computational complexity: ', macs))
    print('{:<30}  {:<8}'.format('Number of parameters: ', params))


if __name__ == "__main__":
	net = Model()
	print_time_paramter_complexity(net, 
		input_size = [(2, 3, 80, 192, 160), (2, 1, 80, 192, 160)])
### 剪枝对FLOPS参数量的影响 神经网络剪枝通过移除不重要的连接或通道来简化模型架构。当一个可学习的乘法参数减少至零时,这实际上消除了相应通道中的所有参数,从而减少了整体参数数量[^1]。 #### 参数量的变化 对于被修剪掉的部分,其对应的权重不再参与前向传播过程,这意味着这部分原本存在的参数将从最终模型中完全去除。因此,随着更多小幅度参数被裁减,整个网络的总参数数目会显著下降。这种策略不仅有助于压缩模型体积,而且能够加速推理速度并降低存储需求。 #### FLOPS 的变化 浮点运算次数 (FLOPS) 主要取决于卷积操作其他密集型计算的数量。由于剪枝主要针对那些贡献较少甚至无用的滤波器及其关联权值实施削减措施,所以可以有效减少不必要的计算负担。具体来说: - **卷积层**:如果某个特定过滤器被标记为冗余并通过设置其缩放因子接近于0来进行删除,则涉及该过滤器的所有输入特征映射与输出之间的乘加运算都将消失; - **全连接层**:同样地,在此阶段内任何变得无关紧要的节点也会连同它们所携带的一切链接一起被淘汰出局; 综上所述,经过合理设计后的剪枝方案能够在保持较高精度的同时大幅缩减所需执行的操作总数,进而实现性能优化的目的。 ```python import torch.nn as nn class PrunedModel(nn.Module): def __init__(self, original_model): super(PrunedModel, self).__init__() # Assuming 'original_model' has been pruned already. self.features = original_model.features def forward(self, x): output = self.features(x) return output # Example usage of comparing FLOPs and parameters before/after pruning from thop import profile input_tensor = torch.randn(1, 3, 224, 224) flops_original, params_original = profile(original_model, inputs=(input_tensor,)) print(f"Original Model - FLOPs: {flops_original}, Parameters: {params_original}") pruned_model = PrunedModel(original_model) flops_pruned, params_pruned = profile(pruned_model, inputs=(input_tensor,)) print(f"Pruned Model - FLOPs: {flops_pruned}, Parameters: {params_pruned}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值