torch.nn.Module.parameters(recurse=True)

参考链接: torch.nn.Module.parameters(recurse=True)

在这里插入图片描述
原文及翻译:

parameters(recurse=True)
	Returns an iterator over module parameters.
	返回一个迭代器,该迭代器可以遍历模块的参数.
	This is typically passed to an optimizer.
	通常用该方法将参数传递给优化器.
	
	Parameters 参数
    recurse (bool)if True, then yields parameters of this 
    module and all submodules. Otherwise, yields only parameters
    that are direct members of this module.
    recurse (bool类型) - 如果rescue是True,那么yield迭代返回出这个模块
    以及该模块的所有子模块的参数. 否则,如果是False,那么只yield迭代返回
    出这个模块的直接成员.
    Yields 迭代返回
    Parameter – module parameter
    Parameter类型 - 模块的参数
    
	Example: 例子:

	>>> for param in model.parameters():
	>>>     print(type(param.data), param.size())
	<class 'torch.FloatTensor'> (20L,)
	<class 'torch.FloatTensor'> (20L, 1L, 5L, 5L)

代码实验展示:

import torch 
import torch.nn as nn
torch.manual_seed(seed=20200910)
class Model(torch.nn.Module):
    def __init__(self):
        super(Model,self).__init__()
        self.conv1=torch.nn.Sequential(  # 输入torch.Size([64, 1, 28, 28])
                torch.nn.Conv2d(1,64,kernel_size=3,stride=1,padding=1),
                torch.nn.ReLU(),  # 输出torch.Size([64, 64, 28, 28])
                torch.nn.Conv2d(64,128,kernel_size=3,stride=1,padding=1),  # 输出torch.Size([64, 128, 28, 28])
                torch.nn.ReLU(),
                torch.nn.MaxPool2d(stride=2,kernel_size=2)  # 输出torch.Size([64, 128, 14, 14])
        )

        self.dense=torch.nn.Sequential(  # 输入torch.Size([64, 14*14*128])
                    torch.nn.Linear(14*14*128,1024),  # 输出torch.Size([64, 1024])
                    torch.nn.ReLU(),
                    torch.nn.Dropout(p=0.5),
                    torch.nn.Linear(1024,10)  # 输出torch.Size([64, 10])        
        )
        self.layer4cxq1 = torch.nn.Conv2d(2,33,4,4)
        self.layer4cxq2 = torch.nn.ReLU()
        self.layer4cxq3 = torch.nn.MaxPool2d(stride=2,kernel_size=2)
        self.layer4cxq4 = torch.nn.Linear(14*14*128,1024)
        self.layer4cxq5 = torch.nn.Dropout(p=0.8)
        self.attribute4cxq = nn.Parameter(torch.tensor(20200910.0))
        self.attribute4lzq = nn.Parameter(torch.tensor([2.0,3.0,4.0,5.0]))    
        self.attribute4hh = nn.Parameter(torch.randn(3,4,5,6))
        self.attribute4wyf = nn.Parameter(torch.randn(7,8,9,10))



    def forward(self,x):  # torch.Size([64, 1, 28, 28])
        x = self.conv1(x)  # 输出torch.Size([64, 128, 14, 14])
        x = x.view(-1,14*14*128)  # torch.Size([64, 14*14*128])
        x = self.dense(x)  # 输出torch.Size([64, 10])
        return x

print('cuda(GPU)是否可用:',torch.cuda.is_available())
print('torch的版本:',torch.__version__)

model = Model() #.cuda()

print("测试模型(CPU)".center(100,"-"))
print(type(model))

print("测试模型parameters(recurse=True)方法".center(100,"-"))
for param in model.parameters(recurse=True):
    print(param.shape)

print('-'*100)
print("测试模型parameters(recurse=False)方法".center(100,"-"))
for param in model.parameters(recurse=False):
    print(param.shape)

控制台输出结果:

Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。

尝试新的跨平台 PowerShell https://aka.ms/pscore6

加载个人及系统配置文件用了 1147 毫秒。
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> conda activate ssd4pytorch1_2_0
(ssd4pytorch1_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>  & 'D:\Anaconda3\envs\ssd4pytorch1_2_0\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2020.12.424452561\pythonFiles\lib\python\debugpy\launcher' '53281' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\test4cxq\test31.py'
cuda(GPU)是否可用: True
torch的版本: 1.2.0+cu92
---------------------------------------------测试模型(CPU)----------------------------------------------
<class '__main__.Model'>
-----------------------------------测试模型parameters(recurse=True)方法-----------------------------------
torch.Size([])
torch.Size([4])
torch.Size([3, 4, 5, 6])
torch.Size([7, 8, 9, 10])
torch.Size([64, 1, 3, 3])
torch.Size([64])
torch.Size([128, 64, 3, 3])
torch.Size([128])
torch.Size([1024, 25088])
torch.Size([1024])
torch.Size([10, 1024])
torch.Size([10])
torch.Size([33, 2, 4, 4])
torch.Size([33])
torch.Size([1024, 25088])
torch.Size([1024])
----------------------------------------------------------------------------------------------------
----------------------------------测试模型parameters(recurse=False)方法-----------------------------------
torch.Size([])
torch.Size([4])
torch.Size([3, 4, 5, 6])
torch.Size([7, 8, 9, 10])
(ssd4pytorch1_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> 

代码实验展示:

import torch
import torch.nn as nn
torch.manual_seed(seed=20200910)

class Model4CXQ(nn.Module):
    def __init__(self):
        super(Model4CXQ, self).__init__()
        # super().__init__()
        self.attribute4cxq = nn.Parameter(torch.tensor(20200910.0))
        self.attribute4lzq = nn.Parameter(torch.tensor(20200.0))
        # self.attribute4scc = nn.Parameter(torch.Tensor(2.0))  # TypeError: new(): data must be a sequence (got float)
        # self.attribute4pq = nn.Parameter(torch.tensor(2))  # RuntimeError: Only Tensors of floating point dtype can require gradients
        self.attribute4zh = nn.Parameter(torch.Tensor(2))
        # self.attribute4yzb = nn.Parameter(torch.tensor(912.0))
        self.attribute4yzb = (torch.tensor(912.0))
        self.attribute4gcx = (torch.tensor(3))
        self.attribute4ymw = (torch.Tensor(3))

    def forward(self, x):
        pass


if __name__ == "__main__":
    model = Model4CXQ()
    print()
    print("打印参数".center(50,'-'))
    for param in model.parameters():
        print(param)

    print('调用named_parameters()'.center(100,"-"))
    for name, param in model.named_parameters():
        print(name,'-->',param)

    print("打印字典".center(50,'-'))
    for k, v in model.state_dict().items():
        print(k, v)

    print()
    print("增加属性".center(50,'-'))
    attribute4cjhT = torch.Tensor(3)
    attribute4cjhP = nn.Parameter(torch.Tensor(2))
    model.attribute4cjhT = attribute4cjhT
    model.attribute4cjhP = attribute4cjhP

    print("打印参数".center(50,'-'))
    for param in model.parameters():
        print(param)

    print('调用named_parameters()'.center(100,"-"))
    for name, param in model.named_parameters():
        print(name,'-->',param)

    print("打印字典".center(50,'-'))
    for k, v in model.state_dict().items():
        print(k, v)




    print()
    print("注册属性".center(50,'-'))
    attribute4cjhRT = torch.Tensor(3)
    attribute4cjhRP = nn.Parameter(torch.Tensor(2))
    # model.register_parameter('attribute4cjhRT', attribute4cjhRT)  
    # 上一行代码报错,注册的应该是Parameter类型,而不是FloatTensor类型
    # 报错信息:
    # TypeError: cannot assign 'torch.FloatTensor' object to parameter 'attribute4cjhRT' (torch.nn.Parameter or None required)
    model.register_parameter('登记注册attribute4cjhRP属性', attribute4cjhRP)

    print("打印参数".center(50,'-'))
    for param in model.parameters():
        print(param)

    print('调用named_parameters()'.center(100,"-"))
    for name, param in model.named_parameters():
        print(name,'-->',param)

    print("打印字典".center(50,'-'))
    for k, v in model.state_dict().items():
        print(k, v)

控制台输出结果:

Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。

尝试新的跨平台 PowerShell https://aka.ms/pscore6

加载个人及系统配置文件用了 979 毫秒。
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> conda activate ssd4pytorch1_2_0
(ssd4pytorch1_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>  & 'D:\Anaconda3\envs\ssd4pytorch1_2_0\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2020.12.424452561\pythonFiles\lib\python\debugpy\launcher' '63993' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\test4cxq\test2.py'

-----------------------打印参数-----------------------
Parameter containing:
tensor(20200910., requires_grad=True)
Parameter containing:
tensor(20200., requires_grad=True)
Parameter containing:
tensor([0., 0.], requires_grad=True)
----------------------------------------调用named_parameters()----------------------------------------
attribute4cxq --> Parameter containing:
tensor(20200910., requires_grad=True)
attribute4lzq --> Parameter containing:
tensor(20200., requires_grad=True)
attribute4zh --> Parameter containing:
tensor([0., 0.], requires_grad=True)
-----------------------打印字典-----------------------
attribute4cxq tensor(20200910.)
attribute4lzq tensor(20200.)
attribute4zh tensor([0., 0.])

-----------------------增加属性-----------------------
-----------------------打印参数-----------------------
Parameter containing:
tensor(20200910., requires_grad=True)
Parameter containing:
tensor(20200., requires_grad=True)
Parameter containing:
tensor([0., 0.], requires_grad=True)
Parameter containing:
tensor([6.5713e+05, 1.5286e-19], requires_grad=True)
----------------------------------------调用named_parameters()----------------------------------------      
attribute4cxq --> Parameter containing:
tensor(20200910., requires_grad=True)
attribute4lzq --> Parameter containing:
tensor(20200., requires_grad=True)
attribute4zh --> Parameter containing:
tensor([0., 0.], requires_grad=True)
attribute4cjhP --> Parameter containing:
tensor([6.5713e+05, 1.5286e-19], requires_grad=True)
-----------------------打印字典-----------------------
attribute4cxq tensor(20200910.)
attribute4lzq tensor(20200.)
attribute4zh tensor([0., 0.])
attribute4cjhP tensor([6.5713e+05, 1.5286e-19])

-----------------------注册属性-----------------------
-----------------------打印参数-----------------------
Parameter containing:
tensor(20200910., requires_grad=True)
Parameter containing:
tensor(20200., requires_grad=True)
Parameter containing:
tensor([0., 0.], requires_grad=True)
Parameter containing:
tensor([6.5713e+05, 1.5286e-19], requires_grad=True)
Parameter containing:
tensor([0., 0.], requires_grad=True)
----------------------------------------调用named_parameters()----------------------------------------      
attribute4cxq --> Parameter containing:
tensor(20200910., requires_grad=True)
attribute4lzq --> Parameter containing:
tensor(20200., requires_grad=True)
attribute4zh --> Parameter containing:
tensor([0., 0.], requires_grad=True)
attribute4cjhP --> Parameter containing:
tensor([6.5713e+05, 1.5286e-19], requires_grad=True)
登记注册attribute4cjhRP属性 --> Parameter containing:
tensor([0., 0.], requires_grad=True)
-----------------------打印字典-----------------------
attribute4cxq tensor(20200910.)
attribute4lzq tensor(20200.)
attribute4zh tensor([0., 0.])
attribute4cjhP tensor([6.5713e+05, 1.5286e-19])
登记注册attribute4cjhRP属性 tensor([0., 0.])
(ssd4pytorch1_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> 
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码定义了一个名为 VGG19Encoder 的神经网络模型。它使用了预训练的 VGG19 模型的前四个卷积层和最后一个全连接层作为特征提取器,其中前四个卷积层被分别用于提取不同层级的特征。然后,通过几个额外的卷积层和全连接层将提取的特征转换为对输入图像中物体类别的预测。其中,提取的特征被分别送入四个全连接层中进行分类。 具体来说,代码中的各个部分的功能如下: - `features_list = list(vgg19.features.children())`:获取 VGG19 模型的所有卷积层。 - `self.conv2_2 = torch.nn.Sequential(*features_list[:13])`:将前 13 层卷积层作为 conv2_2 层。 - `self.conv3_4 = torch.nn.Sequential(*features_list[13:26])`:将第 14 层到第 26 层卷积层作为 conv3_4 层。 - `self.conv4_4 = torch.nn.Sequential(*features_list[26: 39])`:将第 27 层到第 39 层卷积层作为 conv4_4 层。 - `self.conv5_4 = torch.nn.Sequential(*features_list[39:-1])`:将第 40 层到倒数第二层卷积层作为 conv5_4 层。 - `self.tail_layer = features_list[-1]`:将最后一层卷积层作为尾部层。 - `self.fc_layers = list(vgg19.classifier.children())[:-2]`:获取 VGG19 模型的所有全连接层,但不包括最后两层。 - `self.fc_layers = torch.nn.Sequential(*list(self.fc_layers))`:将所有全连接层组成一个新的连续的全连接层。 - `self.extract_0 = torch.nn.Sequential(torch.nn.MaxPool2d(kernel_size=8, stride=8), torch.nn.Conv2d(128, self.k, kernel_size=1, stride=1))`:将 conv2_2 层的输出进行最大池化和卷积操作,以提取更高级别的特征。 - `self.extract_1 = torch.nn.Sequential(torch.nn.MaxPool2d(kernel_size=4, stride=4), torch.nn.Conv2d(256, self.k, kernel_size=1, stride=1))`:将 conv3_4 层的输出进行最大池化和卷积操作,以提取更高级别的特征。 - `self.extract_2 = torch.nn.Sequential(torch.nn.MaxPool2d(kernel_size=2, stride=2), torch.nn.Conv2d(512, self.k, kernel_size=1, stride=1))`:将 conv4_4 层的输出进行最大池化和卷积操作,以提取更高级别的特征。 - `self.extract_3 = torch.nn.Sequential(torch.nn.Conv2d(512, self.k, kernel_size=1, stride=1))`:将 conv5_4 层的输出进行卷积操作,以提取更高级别的特征。 - `self.fc0 = torch.nn.Linear(196, 1, bias=True)`:定义一个输入为 196 的全连接层,用于分类。 - `self.fc1 = torch.nn.Linear(196, 1, bias=True)`:定义第二个输入为 196 的全连接层,用于分类。 - `self.fc2 = torch.nn.Linear(196, 1, bias=True)`:定义第三个输入为 196 的全连接层,用于分类。 - `self.fc3 = torch.nn.Linear(196, 1, bias=True)`:定义第四个输入为 196 的全连接层,用于分类。 - `self.fc4 = torch.nn.Linear(4096, 2 * k, bias=True)`:定义一个输入为 4096 的全连接层,用于分类。 - `self.bn1 = torch.nn.BatchNorm1d(k)`:定义一个 Batch Normalization 层,用于归一化数据。 - `self.bn2 = torch.nn.BatchNorm1d(k)`:定义第二个 Batch Normalization 层,用于归一化数据。 - `weight_init(self.fc0, self.fc1, self.fc2, self.fc3, self.fc4)`:对所有全连接层进行权重初始化,以提高模型的性能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值