首页 > 编程语言 >PyTorch笔记:Python中的state_dict是啥

PyTorch笔记:Python中的state_dict是啥

时间:2022-11-05 20:44:45浏览次数:72  
标签:Python self torch state PyTorch bias dict Size

来自: https://pytorch.org/tutorials/recipes/recipes/what_is_state_dict.html

在PyTorch中,可学习的参数都被保存在模型的parameters中,可以通过model.parameters()访问到。而state_dict则是一个python字典对象,它映射了模型的每个层到参数张量。

Note that only layers with learnable parameters (convolutional layers, linear layers, etc.) and registered buffers (batchnorm’s running_mean) have entries in the model’s state_dict. Optimizer objects (torch.optim) also have a state_dict, which contains information about the optimizer’s state, as well as the hyperparameters used

官方示例:

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
print(net)
# ==== 输出 ====
Net(
  (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)
# Print model's state_dict
print("Model's state_dict:")
for param_tensor in net.state_dict():
    print(param_tensor, "\t", net.state_dict()[param_tensor].size())

print()

# Print optimizer's state_dict
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
    print(var_name, "\t", optimizer.state_dict()[var_name])

输出:

Model's state_dict:
conv1.weight 	 torch.Size([6, 3, 5, 5])
conv1.bias 	 torch.Size([6])
conv2.weight 	 torch.Size([16, 6, 5, 5])
conv2.bias 	 torch.Size([16])
fc1.weight 	 torch.Size([120, 400])
fc1.bias 	 torch.Size([120])
fc2.weight 	 torch.Size([84, 120])
fc2.bias 	 torch.Size([84])
fc3.weight 	 torch.Size([10, 84])
fc3.bias 	 torch.Size([10])

Optimizer's state_dict:
state 	 {}
param_groups 	 [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}]

标签:Python,self,torch,state,PyTorch,bias,dict,Size
From: https://www.cnblogs.com/x-ocean/p/16861030.html

相关文章

  • Python 爬虫之多进程
    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、......
  • python函数
    python函数函数啊函数多解决问题,踩的坑多了,就有经验了函数作用:以功能(完成一件事)为导向的代码块,一个函数就是一个功能.随调随用,不用不调减少代码重复性,增强......
  • 极客编程python入门-字典与SET
    dictPython内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度d={'python':7,"java":234,'go':3,123:567}print(d)p......
  • 【python】pycharm打开时一直加载中怎么办 ?
    前言大家早好、午好、晚好吖~问题描述相信很多刚开始使用pycharm不太熟练的小伙伴,每天一开机打开pycharm总是卡半天,不知道的还以为是电脑卡了或者啥问题的。莫慌,其实......
  • 运行python脚本报错:selenium.common.exceptions.SessionNotCreatedException: Message
    运行python脚本报错:selenium.common.exceptions.SessionNotCreatedException:Message:sessionnotcreated        原因:ChromeDriver版本与浏览器版本不......
  • PyTorch笔记:Modules官方文档
    来自https://pytorch.org/docs/stable/notes/modules.htmlASimpleCustomModuleimporttorchfromtorchimportnnclassMyLinear(nn.Module):def__init__(se......
  • python print 打印延迟问题解决
    转载:https://wenku.baidu.com/view/ffc89347bb4ae45c3b3567ec102de2bd9705de56.html?wkts=1667639107060&bdQuery=python+print%E7%AB%8B%E5%8D%B3%E6%89%93%E5%8D%B0......
  • List泛型数组 Dictionary字典
    泛型数组usingSystem.Collections.Generic;为了解决动态数组的拆装箱问题,故引入泛型数组。//创建一个int类型的泛型数组List<int>list=newList<int>();//数据......
  • 【Python零基础入门篇 · 4】:字符串的运算符、下标和切片
    字符串名称中文名称作用举例str字符串字符串“hello”,”loveyou”,.......字符串的运算符:+*innotin字符串的运算符作用举例结果......
  • Python 函数
    1.1defx():foriinrange(3):print("python")print(x())1.2defx(name):foriinrange(3):print(f"python{name}。")print(x("ILOVE"))1.3defa(name,tim......