手把手教你量化网络(1)网络各层权重参数的查看

一、关键代码与效果展示

代码:

from matplotlib import pyplot as plt

def plot_weights(model):
    modules = [module for module in model.modules()]
    num_sub_plot = 0
    for i, layer in enumerate(modules):
        if hasattr(layer, 'weight'):
            plt.subplot(221+num_sub_plot)
            w = layer.weight.data
            w_one_dim = w.cpu().numpy().flatten()
            plt.hist(w_one_dim, bins=50)
            num_sub_plot += 1
    plt.show()
	
plot_weights(model)
plot_weights(quant_model)

效果:

未量化前的网络权重参数分布概览

量化后的网络权重参数分布概览

可以看到上图所示代码可视化了未量化前的网络权重参数和量化后的网络权重参数,总体可分为两步进行,第一步是读取网络权重参数,第二步是可视化权重参数

二、读取网络权重参数

代码:

modules = [module for module in model.modules()]
print("="*10)
print("网络结构如下所示:")
for i, layer in enumerate(modules):
    print(i,layer)
    
print("="*10)
print("其中具有权重参数的层为:")    
for i, layer in enumerate(modules):
    if hasattr(layer, 'weight'):
        print(i,layer)
        #print(layer.weight)
        #print(layer.weight.data)

思路是借用 nn.model.modules() 函数获取网络各层,然后再迭代判断哪些层具有 weight 属性,即存在权重参数。

结果:

可以看到只有卷积层和线性层具有权重参数,该网络一共是有四个层具有权重参数。

三、可视化权重参数

所以要绘制四个子图,用 matplotlib.pyplot.hist函数即可完成直方图的绘制,思路就是迭代读取网络各层权重参数,然后每读取一层具有权重参数的网络就绘制对应的频数直方图。

  • 5
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪天鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值