news 2026/5/19 10:21:33

深度学习速成:模型的使用与修改,保存与读取

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
深度学习速成:模型的使用与修改,保存与读取

1.使用与修改

VGG16为例

import torchvision import torch #trian_data=torchvision.datasets.imagenet("../data_imgnet",train=True,transform=torchvision.transforms.ToTensor(),download=True) vgg16_false=torchvision.models.vgg16(pretrained=False) vgg16_true=torchvision.models.vgg16(weights=torchvision.models.VGG16_Weights.IMAGENET1K_V1) print(vgg16_true) #vgg16_true.add_module("new_fc",torch.nn.Linear(1000,10))#追加全結合層 vgg16_true.classifier.add_module("new_fc",torch.nn.Linear(1000,10))#追加全結合層 print(vgg16_true) print(vgg16_false) vgg16_false.classifier[6]=torch.nn.Linear(4096,10)#在(6)那里修改全连接层 print(vgg16_false)

修改完的输出

2.保存与读取

2.1保存

import torch import torchvision import torch.nn as nn vgg16=torchvision.models.vgg16(weights=None) #保存1 保存整个模型(结构+参数) torch.save(vgg16,"vgg16.pth") #保存2 只保存模型参数(官方推荐,内存小) torch.save(vgg16.state_dict(),"vgg16_params.pth") class tudui(nn.Module): def __init__(self): super().__init__() self.conv1=nn.Conv2d(3,32,5,padding=2)# self.maxpool1=nn.MaxPool2d(2)# self.conv2=nn.Conv2d(32,32,5,padding=2) self.maxpool2=nn.MaxPool2d(2) self.conv3=nn.Conv2d(32,64,5,padding=2) self.maxpool3=nn.MaxPool2d(2) self.flatten=nn.Flatten()# self.linear1=nn.Linear(1024,64)# self.linear2=nn.Linear(64,10)# def forward(self,x): x=self.conv1(x) x=self.maxpool1(x) x=self.conv2(x) x=self.maxpool2(x) x=self.conv3(x) x=self.maxpool3(x) x=self.flatten(x) x=self.linear1(x) x=self.linear2(x) return x tudui_model=tudui() torch.save(tudui_model,"tudui_params.pth")#方法一保存

2.2 读取

import torch import torchvision from model_save import * #方式一 加载模型 """ vgg16=torch.load("vgg16.pth") print(vgg16) """ #方式二 加载模型参数 vgg16=torchvision.models.vgg16(weights=None) vgg16.load_state_dict(torch.load("vgg16_params.pth")) print(vgg16) """ vgg16_params=torch.load("vgg16_params.pth")#字典形式 print(vgg16_params) """ #方式一有陷阱 需要能访问到save时的类定义 im model=torch.load("tudui_params.pth") print(model)

2.3输出结果

(base) PS E:\desktop\deeplearning> & D:\miniconda3\envs\pytorch_py312\python.exe e:/desktop/deeplearning/src/model_load.py e:\desktop\deeplearning\src\model_load.py:10: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature. vgg16.load_state_dict(torch.load("vgg16_params.pth")) VGG( (features): Sequential( (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): ReLU(inplace=True) (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (3): ReLU(inplace=True) (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (6): ReLU(inplace=True) (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (8): ReLU(inplace=True) (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (11): ReLU(inplace=True) (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (13): ReLU(inplace=True) (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (15): ReLU(inplace=True) (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (18): ReLU(inplace=True) (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (20): ReLU(inplace=True) (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (22): ReLU(inplace=True) (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (25): ReLU(inplace=True) (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (27): ReLU(inplace=True) (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (29): ReLU(inplace=True) (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) ) (avgpool): AdaptiveAvgPool2d(output_size=(7, 7)) (classifier): Sequential( (0): Linear(in_features=25088, out_features=4096, bias=True) (1): ReLU(inplace=True) (2): Dropout(p=0.5, inplace=False) (3): Linear(in_features=4096, out_features=4096, bias=True) (4): ReLU(inplace=True) (5): Dropout(p=0.5, inplace=False) (6): Linear(in_features=4096, out_features=1000, bias=True) ) ) e:\desktop\deeplearning\src\model_load.py:19: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature. model=torch.load("tudui_params.pth") tudui( (conv1): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)) (maxpool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)) (maxpool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv3): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)) (maxpool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (flatten): Flatten(start_dim=1, end_dim=-1) (linear1): Linear(in_features=1024, out_features=64, bias=True) (linear2): Linear(in_features=64, out_features=10, bias=True) )
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/10 13:02:52

谣言只是表象,投资者耐心正在耗尽!

一,市场强势反弹,把前天跌掉的大部分失地都收回来了,但目前看,这还只能算反弹,不是反转。前面重兵把守的 4100 点,现在就是市场的 “天王山”,能不能拿下,是本周最关键的任务。尐程序…

作者头像 李华
网站建设 2026/5/8 18:34:13

软件测试项目实战,Web测试常用测试点,即拿即用宝典

前言 由于web应用与用户直接相关,又通常需要承受长时间的大量操作,因此web项目的功能和性能都必须经过可靠的验证。 这就要经过web项目的全面测试。Web应用程序测试与其它任何一种类型的应用程序测试相比没有太大差别。Web的流行和无所不在&#xff0c…

作者头像 李华
网站建设 2026/5/17 9:47:58

Fiddler抓取HTTPS最全(强)攻略

对于想抓取HTTPS的测试初学者来说,常用的工具就是fiddler。 但是初学时,大家对于fiddler如何抓取HTTPS难免走歪路,也许你一步步按着网上的帖子成功了,这自然是极好的。 但也有可能没那么幸运,这时候你就会很抓狂。 …

作者头像 李华
网站建设 2026/5/13 0:21:21

DeepSeek架构新探索!开源OCR 2诞生!

DeepSeek架构新探索!开源OCR 2诞生! 此前,DeepSeek-OCR的首次问世,已引发视觉压缩领域的广泛关注与学术探讨;而在本次迭代中,DeepSeek研发团队聚焦视觉编码模块开展核心技术升级。值得关注的是,…

作者头像 李华
网站建设 2026/5/9 14:53:18

直播平台主播们的换妆功能是如何实现的?深入了解美颜SDK功能开发

当你在直播平台刷到一位主播,轻点屏幕就能在“清新裸妆”“元气桃花妆”“高级冷白皮”之间自由切换时,很多人会下意识以为: “这不就是个滤镜吗?” 但真正做过直播系统或音视频开发的人都知道——直播换妆,远不只是贴…

作者头像 李华
网站建设 2026/5/11 4:18:35

【FFmpeg使用指南】Part 2:滤镜图架构与信号处理

📚 写给开发者的音视频处理工程手册 🎯 目标:深入解析 FFmpeg 的核心引擎——滤镜图 (Filtergraph)。本章将从信号流(Signal Flow)的角度,阐述如何通过有向图(Directed Graph)结构实…

作者头像 李华