基于Fashion-MNIST数据集的模型剪枝(下)

简介: 1. 介绍1.1 背景介绍目前在深度学习中存在一些困境,对于移动是设备来说,主要是算不好;穿戴设备算不来;数据中心,大多数人又算不起 。这就是做模型做压缩与加速的初衷。

4. 对模型进行剪枝

4.1 构建剪枝网络

import torch
import torch.nn.utils.prune as prune
class Pruning:
    #net_path是修建的模型,amount是模型的修建率
    def __init__(self, net_path, amount):
        self.net = MyNet()
        #加载模型
        self.net.load_state_dict(torch.load(net_path))
        #将模型都定义为元组,这是全局修剪的方法
        self.parameters_to_prune = (
            (self.net.conv1, 'weight'),
            (self.net.conv2, 'weight'),
            (self.net.conv3, 'weight'),
            (self.net.linear1, 'weight'),
            (self.net.linear2, 'weight'),
        )
        self.amount = amount
    def pruning(self):
      #全局修剪参数,方法是修剪绝对值参数
        prune.global_unstructured(
            self.parameters_to_prune,
            pruning_method=prune.L1Unstructured,
            amount=self.amount,
        )
        # print(self.net.state_dict().keys())
        # 删除weight_orig 、weight_mask以及forward_pre_hook
        prune.remove(self.net.conv1, 'weight')
        prune.remove(self.net.conv2, 'weight')
        prune.remove(self.net.conv3, 'weight')
        prune.remove(self.net.linear1, 'weight')
        prune.remove(self.net.linear2, 'weight')
        print(
            "Sparsity in conv1.weight: {:.2f}%".format(
                100. * float(torch.sum(self.net.conv1.weight == 0))
                / float(self.net.conv1.weight.nelement())
            )
        )
        print(
            "Sparsity in conv2.weight: {:.2f}%".format(
                100. * float(torch.sum(self.net.conv2.weight == 0))
                / float(self.net.conv2.weight.nelement())
            )
        )
        print(
            "Sparsity in conv3.weight: {:.2f}%".format(
                100. * float(torch.sum(self.net.conv3.weight == 0))
                / float(self.net.conv3.weight.nelement())
            )
        )
        print(
            "Sparsity in linear1.weight: {:.2f}%".format(
                100. * float(torch.sum(self.net.linear1.weight == 0))
                / float(self.net.linear1.weight.nelement())
            )
        )
        print(
            "Sparsity in linear2.weight: {:.2f}%".format(
                100. * float(torch.sum(self.net.linear2.weight == 0))
                / float(self.net.linear2.weight.nelement())
            )
        )
        print(
            "Global sparsity: {:.2f}%".format(
                100. * float(
                    torch.sum(self.net.conv1.weight == 0)
                    + torch.sum(self.net.conv2.weight == 0)
                    + torch.sum(self.net.conv3.weight == 0)
                    + torch.sum(self.net.linear1.weight == 0)
                    + torch.sum(self.net.linear2.weight == 0)
                )
                / float(
                    self.net.conv1.weight.nelement()
                    + self.net.conv2.weight.nelement()
                    + self.net.conv3.weight.nelement()
                    + self.net.linear1.weight.nelement()
                    + self.net.linear2.weight.nelement()
                )
            )
        )
        # torch.save(self.net.state_dict(), "models/pruned_net_with_conv.pth")
        torch.save(self.net.state_dict(), f"./model/pruned_net_with_torch_{self.amount:.1f}_l1.pth")
if __name__ == '__main__':
    for i in range(1, 10):
        pruning = Pruning("./model/finsh_minst_net.pth", 0.1 * i)
        pruning.pruning()

5. 检测

class Detector:
    def __init__(self, net_path):
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.net = MyNet().to(self.device)
        self.map_location = None if torch.cuda.is_available() else lambda storage, loc: storage
        self.net.load_state_dict(torch.load(net_path, map_location=self.map_location))
        self.net.eval()
    def detect(self,test_data):
        test_loss = 0
        correct = 0
        start = time.time()
        with torch.no_grad():
            for data, label in test_data:
                data, label = data.to(self.device), label.to(self.device)
                output = self.net(data)
                test_loss += self.net.get_loss(output, label)
                pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
                correct += pred.eq(label.view_as(pred)).sum().item()
        end = time.time()
        print(f"total time:{end - start}")
        test_loss /= len(test_data.dataset)
        print('Test: average loss: {:.4f}, accuracy: {}/{} ({:.0f}%)\n'.format(
            test_loss, correct, len(test_data.dataset),
            100. * correct / len(test_data.dataset)))
        #返回的损失和正确率
        return [test_loss,correct/len(test_data.dataset)]
if __name__ == '__main__':
    print("./model/finsh_minst_net.pth")
    test_loss,accuracy,Parameter_compression_ratio = [],[],[]
    detector1 = Detector("./model/finsh_minst_net.pth")
    loss,acc = detector1.detect(test_data)
    test_loss.append(loss)
    accuracy.append(acc)   
    Parameter_compression_ratio.append(0)
    for i in range(1, 10):
        amount = 0.1 * i
        print(f"./model/pruned_net_with_torch_{amount:.1f}_l1.pth")
        detector1 = Detector(f"./model/pruned_net_with_torch_{amount:.1f}_l1.pth")
        loss,acc = detector1.detect(test_data)
        test_loss.append(loss)
        accuracy.append(acc)   
        Parameter_compression_ratio.append(amount)
./model/finsh_minst_net.pth
total time:1.6475636959075928
Test: average loss: 0.0027, accuracy: 9179/10000 (92%)
./model/pruned_net_with_torch_0.1_l1.pth
total time:1.3875453472137451
Test: average loss: 0.0027, accuracy: 9179/10000 (92%)
./model/pruned_net_with_torch_0.2_l1.pth
total time:1.5390675067901611
Test: average loss: 0.0027, accuracy: 9179/10000 (92%)
./model/pruned_net_with_torch_0.3_l1.pth
total time:1.356163501739502
Test: average loss: 0.0026, accuracy: 9178/10000 (92%)
./model/pruned_net_with_torch_0.4_l1.pth
total time:1.4721436500549316
Test: average loss: 0.0026, accuracy: 9163/10000 (92%)
./model/pruned_net_with_torch_0.5_l1.pth
total time:1.429352045059204
Test: average loss: 0.0026, accuracy: 9134/10000 (91%)
./model/pruned_net_with_torch_0.6_l1.pth
total time:1.3589565753936768
Test: average loss: 0.0026, accuracy: 9119/10000 (91%)
./model/pruned_net_with_torch_0.7_l1.pth
total time:1.3456928730010986
Test: average loss: 0.0028, accuracy: 9026/10000 (90%)
./model/pruned_net_with_torch_0.8_l1.pth
total time:1.351386308670044
Test: average loss: 0.0046, accuracy: 8644/10000 (86%)
./model/pruned_net_with_torch_0.9_l1.pth
total time:1.4840266704559326
Test: average loss: 0.0135, accuracy: 7021/10000 (70%)
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1,2,figsize=(9,5))
ax1 = plt.subplot(121)  #绘制子图1对象
ax2 = plt.subplot(122)  #绘制子图2对象
x = Parameter_compression_ratio
y = accuracy
y2 = test_loss
ax1.plot(x,y,color='red',label='accuracy')
ax2.plot(x,y2,color='blue',label='test_loss')
ax1.legend()
ax2.legend()
plt.show()

相关文章
|
计算机视觉
教你如何玩转Modelscope (一、图片编辑与描述生成)
本文通过一个有趣的图片处理例子,教你如何利用modelscope强大且多样的模型能力去解锁你专属的图片编辑能力。
4074 1
教你如何玩转Modelscope (一、图片编辑与描述生成)
|
机器学习/深度学习 数据可视化 数据挖掘
初学者该如何选择最适合自己的图像分类模型
初学者该如何选择最适合自己的图像分类模型
2817 0
初学者该如何选择最适合自己的图像分类模型
|
机器学习/深度学习 人工智能 编解码
|
机器学习/深度学习 自然语言处理 算法
文本摘要(text summarization)任务:研究范式,重要模型,评估指标(持续更新ing...)
本文是作者在学习文本摘要任务的过程中,根据学习资料总结逐步得到并整理为成文的相关内容。相关学习资料(包括论文、博文、视频等)都会以脚注等形式标明。有一些在一篇内会导致篇幅过长的内容会延伸到其他博文中撰写,但会在本文中提供超链接。 本文将主要列举里程碑式的重要文本摘要论文。 注意:除文首的表格外,本文所参考的论文,如本人已撰写对应的学习博文,则不直接引用原论文,而引用我撰写的博文。 本文会长期更新。
文本摘要(text summarization)任务:研究范式,重要模型,评估指标(持续更新ing...)
|
人工智能 自然语言处理 API
浅谈ModelScope
ModelScope是阿里推出的下一代开源的模型即服务共享平台,为泛AI开发者提供灵活、易用、低成本的一站式模型服务产品,其开发目标为让模型应用更简单。ModelScope希望在汇集行业领先的预训练模型,减少开发者的重复研发成本,提供更加绿色环保、开源开放的AI开发环境和模型服务,助力绿色“数字经济”事业的建设。ModelScope平台以开源的方式提供了多类优质模型,开发者可在平台上免费体验与下载使用。
|
存储 算法 关系型数据库
向量数据库深度剖析:核心优劣势 + 适用场景,避开 RAG 落地的选型坑
本文深度剖析向量数据库:揭示其在RAG系统中实现语义检索的核心价值与六大优势,直面模型依赖强、模糊匹配、硬件成本高、不支持事务等五大劣势,并给出精准选型指南与落地避坑策略,助你选对工具、用好RAG。
|
机器人 异构计算
10分钟,用RAG搭建专业钉钉/飞书客服机器人
只需10分钟,快速搭建专属客服机器人,大幅提升工作效率!通过魔搭社区注册账号、绑定阿里云账号获取免费算力资源,并选择GPU模式运行教程脚本。按照食用指引操作,完成机器人部署并进行对话测试,前5位在评论区提交作业的用户将获赠魔搭社区时尚咖啡杯一个。立即点击教程脚本链接开始体验吧!
706 0
|
机器学习/深度学习 自然语言处理 算法
大模型微调PPO原理——零基础吃透RLHF核心算法
本文通俗解析PPO算法——RLHF微调的核心技术:以“人类反馈→奖励模型→策略优化”三步闭环,辅以“近端约束”保障稳定,让大模型不仅答得对,更答得让人满意。零基础也能轻松理解+上手实操。
|
人工智能 自然语言处理 安全
PPO应用——大模型偏好优化的核心场景与落地实践
本文详解PPO在大模型中的实战应用:涵盖对话风格优化、内容质量提升、安全合规控制及垂直领域微调四大场景,揭示“反馈-量化-优化”落地逻辑,并推荐零门槛实操平台,助力新手快速赋能业务。
|
机器学习/深度学习 算法 安全
大模型微调 PPO 原理 —— 零基础也能懂的强化学习微调逻辑
本文通俗解析PPO算法在大模型RLHF微调中的核心作用:以人类反馈为依据,通过奖励模型量化偏好,借助“近端约束”实现安全、稳定、渐进的策略优化,解决传统微调无偏好导向与更新不稳的痛点。零基础可懂,附实操平台入口。

热门文章

最新文章