Pytorch 统计模型参数量的操作 param.numel()

param.numel()

返回param中元素的数量

统计模型参数量

num_params = sum(param.numel() for param in net.parameters())
print(num_params)

补充:Pytorch 查看模型参数

Pytorch 查看模型参数

查看利用Pytorch搭建模型的参数,直接看程序

import torch
# 引入torch.nn并指定别名
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        # nn.Module子类的函数必须在构造函数中执行父类的构造函数
        super(Net, self).__init__()

        # 卷积层 '1'表示输入图片为单通道, '6'表示输出通道数,'3'表示卷积核为3*3
        self.conv1 = nn.Conv2d(1, 6, 3)
        #线性层,输入1350个特征,输出10个特征
        self.fc1   = nn.Linear(1350, 10)  #这里的1350是如何计算的呢?这就要看后面的forward函数
    #正向传播
    def forward(self, x):
        print(x.size()) # 结果:[1, 1, 32, 32]
        # 卷积 -> 激活 -> 池化
        x = self.conv1(x) #根据卷积的尺寸计算公式,计算结果是30,具体计算公式后面第二张第四节 卷积神经网络 有详细介绍。
        x = F.relu(x)
        print(x.size()) # 结果:[1, 6, 30, 30]
        x = F.max_pool2d(x, (2, 2)) #我们使用池化层,计算结果是15
        x = F.relu(x)
        print(x.size()) # 结果:[1, 6, 15, 15]
        # reshape,‘-1'表示自适应
        #这里做的就是压扁的操作 就是把后面的[1, 6, 15, 15]压扁,变为 [1, 1350]
        x = x.view(x.size()[0], -1)
        print(x.size()) # 这里就是fc1层的的输入1350
        x = self.fc1(x)
        return x

net = Net()
for parameters in net.parameters():
    print(parameters)

输出为:

Parameter containing:
tensor([[[[-0.0104, -0.0555, 0.1417],
[-0.3281, -0.0367, 0.0208],
[-0.0894, -0.0511, -0.1253]]],

[[[-0.1724, 0.2141, -0.0895],
[ 0.0116, 0.1661, -0.1853],
[-0.1190, 0.1292, -0.2451]]],

[[[ 0.1827, 0.0117, 0.2880],
[ 0.2412, -0.1699, 0.0620],
[ 0.2853, -0.2794, -0.3050]]],

[[[ 0.1930, 0.2687, -0.0728],
[-0.2812, 0.0301, -0.1130],
[-0.2251, -0.3170, 0.0148]]],

[[[-0.2770, 0.2928, -0.0875],
[ 0.0489, -0.2463, -0.1605],
[ 0.1659, -0.1523, 0.1819]]],

[[[ 0.1068, 0.2441, 0.3160],
[ 0.2945, 0.0897, 0.2978],
[ 0.0419, -0.0739, -0.2609]]]])
Parameter containing:
tensor([ 0.0782, 0.2679, -0.2516, -0.2716, -0.0084, 0.1401])
Parameter containing:
tensor([[ 1.8612e-02, 6.5482e-03, 1.6488e-02, ..., -1.3283e-02,
1.8715e-02, 5.4037e-03],
[ 1.8569e-03, 1.8022e-02, -2.3465e-02, ..., 1.6527e-03,
2.0443e-02, -2.2009e-02],
[ 9.9104e-03, 6.6134e-03, -2.7171e-02, ..., -5.7119e-03,
2.4532e-02, 2.2284e-02],
...,
[ 6.9182e-03, 1.7279e-02, -1.7783e-03, ..., 1.9354e-02,
2.1105e-03, 8.6245e-03],
[ 1.6877e-02, -1.2414e-02, 2.2409e-02, ..., -2.0604e-02,
1.3253e-02, -3.6008e-03],
[-2.1598e-02, 2.5892e-02, 1.9372e-02, ..., 1.4159e-02,
7.0983e-03, -2.3713e-02]])
Parameter containing:
tensor(1.00000e-02 *
[ 1.4703, 1.0289, 2.5069, -2.2603, -1.5218, -1.7019, 1.2569,
0.4617, -2.3082, -0.6282])

for name,parameters in net.named_parameters():
    print(name,':',parameters.size())

输出:

conv1.weight : torch.Size([6, 1, 3, 3])
conv1.bias : torch.Size([6])
fc1.weight : torch.Size([10, 1350])
fc1.bias : torch.Size([10])

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • pytorch 求网络模型参数实例

    用pytorch训练一个神经网络时,我们通常会很关心模型的参数总量.下面分别介绍来两种方法求模型参数 一 .求得每一层的模型参数,然后自然的可以计算出总的参数. 1.先初始化一个网络模型model 比如我这里是 model=cliqueNet(里面是些初始化的参数) 2.调用model的Parameters类获取参数列表 一个典型的操作就是将参数列表传入优化器里.如下 optimizer = optim.Adam(model.parameters(), lr=opt.lr) 言归正传,继续回到参

  • PyTorch和Keras计算模型参数的例子

    Pytorch中,变量参数,用numel得到参数数目,累加 def get_parameter_number(net): total_num = sum(p.numel() for p in net.parameters()) trainable_num = sum(p.numel() for p in net.parameters() if p.requires_grad) return {'Total': total_num, 'Trainable': trainable_num} Kera

  • pytorch 实现打印模型的参数值

    对于简单的网络 例如全连接层Linear 可以使用以下方法打印linear层: fc = nn.Linear(3, 5) params = list(fc.named_parameters()) print(params.__len__()) print(params[0]) print(params[1]) 输出如下: 由于Linear默认是偏置bias的,所有参数列表的长度是2.第一个存的是全连接矩阵,第二个存的是偏置. 对于稍微复杂的网络 例如MLP mlp = nn.Sequential

  • pytorch获取模型某一层参数名及参数值方式

    1.Motivation: I wanna modify the value of some param; I wanna check the value of some param. The needed function: 2.state_dict() #generator type model.modules()#generator type named_parameters()#OrderDict type from torch import nn import torch #creat

  • Pytorch 统计模型参数量的操作 param.numel()

    param.numel() 返回param中元素的数量 统计模型参数量 num_params = sum(param.numel() for param in net.parameters()) print(num_params) 补充:Pytorch 查看模型参数 Pytorch 查看模型参数 查看利用Pytorch搭建模型的参数,直接看程序 import torch # 引入torch.nn并指定别名 import torch.nn as nn import torch.nn.functio

  • Pytorch - TORCH.NN.INIT 参数初始化的操作

    路径: https://pytorch.org/docs/master/nn.init.html#nn-init-doc 初始化函数:torch.nn.init # -*- coding: utf-8 -*- """ Created on 2019 @author: fancp """ import torch import torch.nn as nn w = torch.empty(3,5) #1.均匀分布 - u(a,b) #torch.n

  • pytorch 共享参数的示例

    在很多神经网络中,往往会出现多个层共享一个权重的情况,pytorch可以快速地处理权重共享问题. 例子1: class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.conv_weight = nn.Parameter(torch.randn(3, 3, 5, 5)) def forward(self, x): x = nn.functional.conv2d(x, self.conv_w

  • Pytorch 高效使用GPU的操作

    前言 深度学习涉及很多向量或多矩阵运算,如矩阵相乘.矩阵相加.矩阵-向量乘法等.深层模型的算法,如BP,Auto-Encoder,CNN等,都可以写成矩阵运算的形式,无须写成循环运算.然而,在单核CPU上执行时,矩阵运算会被展开成循环的形式,本质上还是串行执行.GPU(Graphic Process Units,图形处理器)的众核体系结构包含几千个流处理器,可将矩阵运算并行化执行,大幅缩短计算时间.随着NVIDIA.AMD等公司不断推进其GPU的大规模并行架构,面向通用计算的GPU已成为加速可并

  • 微信小程序学习笔记之跳转页面、传递参数获得数据操作图文详解

    本文实例讲述了微信小程序学习笔记之跳转页面.传递参数获得数据操作.分享给大家供大家参考,具体如下: 前面一篇介绍了微信小程序表单提交与PHP后台数据交互处理.现在需要实现点击博客标题或缩略图,跳转到博客详情页面. 开始想研究一下微信小程序的web-view组件跳转传参,把网页嵌入到小程序,结果看到官方文档的一句话打消了念头,因为没有认证...... [方法一 使用navigator组件跳转传参] 前台博客列表页面data.wxml:(后台数据交互参考上一篇) <view wx:for="{

  • pytorch 固定部分参数训练的方法

    需要自己过滤 optimizer.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-3) 另外,如果是Variable,则可以初始化时指定 j = Variable(torch.randn(5,5), requires_grad=True) 但是如果是 m = nn.Linear(10,10) 是没有requires_grad传入的 m.requires_grad也没有 需要 for i in m.parameter

  • pytorch 自定义参数不更新方式

    nn.Module中定义参数:不需要加cuda,可以求导,反向传播 class BiFPN(nn.Module): def __init__(self, fpn_sizes): self.w1 = nn.Parameter(torch.rand(1)) print("no---------------------------------------------------",self.w1.data, self.w1.grad) 下面这个例子说明中间变量可能没有梯度,但是最终变量有梯度

  • Tensorflow实现部分参数梯度更新操作

    在深度学习中,迁移学习经常被使用,在大数据集上预训练的模型迁移到特定的任务,往往需要保持模型参数不变,而微调与任务相关的模型层. 本文主要介绍,使用tensorflow部分更新模型参数的方法. 1. 根据Variable scope剔除需要固定参数的变量 def get_variable_via_scope(scope_lst): vars = [] for sc in scope_lst: sc_variable = tf.get_collection(tf.GraphKeys.TRAINAB

  • pytorch快速搭建神经网络_Sequential操作

    之前用Class类来搭建神经网络 class Neuro_net(torch.nn.Module): """神经网络""" def __init__(self, n_feature, n_hidden_layer, n_output): super(Neuro_net, self).__init__() self.hidden_layer = torch.nn.Linear(n_feature, n_hidden_layer) self.outp

  • Mybatis Mapper中多参数方法不使用@param注解报错的解决

    目录 问题描述 寻求解决方案 寻找原因 拓展延伸 在使用低版本的Mybatis的时候,Mapper中的方法如果有多个参数时需要使用@param注解,才能在对应xml的sql语句中使用参数名称获取传入方法的参数值,否则就会报错.本文结合自身在真实开发环境中使用IDEA开发时遇到的问题来共同探讨一下不使用@Param注解报错背后的原因以及解决方案. 问题描述 最近使用IDEA进行开发,项目使用SpringBoot+Mybatis3.4.6,同样的代码检出到本地IDEA后运行,在一个业务查询模块报错,

随机推荐