torch.nn.Parameter()函数

news2024/10/7 14:31:03

引言

在很多经典网络结构中都有nn.Parameter()这个函数,故对其进行了解

pytorch官方介绍:
在这里插入图片描述

语法结构:

torch.nn.parameter.Parameter(data=None, requires_grad=True)
"""
data (Tensor) – parameter tensor. —— 输入得是一个tensor。
requires_grad (bool, optional) – if the parameter requires gradient. See Locally disabling gradient computation for more details。
Default: True —— 这个不用解释,需要注意的是nn.Parameter()默认有梯度。
"""

torch.nn.Parameter继承torch.Tensor,其作用将一个不可训练的类型为Tensor的参数转化为可训练的类型为parameter的参数,并将这个参数绑定到module里面,成为module中可训练的参数。

torch.nn.Parameter(Tensor data, bool requires_grad)

其中:data为传入Tensor类型参数,requires_grad默认值为True,表示可训练,False表示不可训练。

以nn.Linear为例:

class Linear(Module):
    r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        bias: If set to ``False``, the layer will not learn an additive bias.
            Default: ``True``
    Shape:
        - Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
          additional dimensions and :math:`H_{in} = \text{in\_features}`
        - Output: :math:`(N, *, H_{out})` where all but the last dimension
          are the same shape as the input and :math:`H_{out} = \text{out\_features}`.
    Attributes:
        weight: the learnable weights of the module of shape
            :math:`(\text{out\_features}, \text{in\_features})`. The values are
            initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
            :math:`k = \frac{1}{\text{in\_features}}`
        bias:   the learnable bias of the module of shape :math:`(\text{out\_features})`.
                If :attr:`bias` is ``True``, the values are initialized from
                :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
                :math:`k = \frac{1}{\text{in\_features}}`
    Examples::
        >>> m = nn.Linear(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])
    """
    __constants__ = ['in_features', 'out_features']

    def __init__(self, in_features, out_features, bias=True):
        super(Linear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = Parameter(torch.Tensor(out_features, in_features))
        if bias:
            self.bias = Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

    def reset_parameters(self):
        init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)

    def forward(self, input):
        return F.linear(input, self.weight, self.bias)

    def extra_repr(self):
        return 'in_features={}, out_features={}, bias={}'.format(
            self.in_features, self.out_features, self.bias is not None
        )

注解:

  1. 在__init__(self, in_features, out_features,
    bias=True)中初始化两个参数:self.weight和self.bias。
  2. self.weight = Parameter(torch.Tensor(out_features,
    in_features))定义一个形状为(out_features, in_features)可训练参数。
  3. self.bias同理。
  4. 与torch.tensor([1,2,3],requires_grad=True)的区别,这个只是将参数变成可训练的,并没有绑定在module的parameter列表中。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1015085.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

聊聊Spring事务同步器TransactionSynchronization

在一些业务场景中可能我们需要去对某一个spring事务的生命周期进行监控,比如在这个事务提交,回滚,被挂起的时候,我们想要去执行一些自定义的操作,这怎么去做呢?其实spring作为一个高扩展性的框架&#xff0…

中秋特辑:Java事件监听实现一个猜灯谜小游戏

众所周知,JavaSwing是Java中关于窗口开发的一个工具包,可以开发一些窗口程序,然后由于工具包的一些限制,导致Java在窗口开发商并没有太多优势(当然也有一些第三方的工具包也很好用),不过&#x…

使用Python CV2融合人脸到新图片--优化版

优化说明 上一版本人脸跟奥特曼图片合并后边界感很严重,于是查找资料发现CV2还有一个泊松函数很适合融合图像。具体代码如下: import numpy as np import cv2usrFilePath "newpic22.jpg" atmFilePath "atm2.jpg" src cv2.imrea…

java基础-集合-ArrayList(JDK1.8)源码学习

文章目录 类图新增addensureCapacityInternalensureExplicitCapacitygrowhugeCapacity 删除removefastRemove 遍历Iterator 类图 新增 add public boolean add(E e) {// 根据注释可知 Increments modCount!!,modCount下面详解ensureCapacityInternal(size 1); //…

特斯拉Dojo超算:AI训练平台的自动驾驶与通用人工智能之关键

特斯拉公开Dojo超算架构细节,AI训练算力平台成为其自动驾驶与通用人工智能布局的关键一环 在近日举行的Hot Chips 34会议上,特斯拉披露了其自主研发的AI超算Dojo的详细信息。Dojo是一个可定制的超级计算机,从芯片到系统全部由特斯拉自主设计…

如何优化网站SEO(百度SEO优化的6个方案及密度)

一:蘑菇号https://www.mooogu.cn/ SEO优化是提高网站在搜索引擎中排名的关键技术。对于新网站而言,如何快速提高百度排名是每个站长需要关注的问题。下面我们将介绍新网站百度SEO具体方法。 二: 首先,通过网站架构优化来提高页…

解决5053无法安装驱动的故障

用5053连接车机,发现驱动上面有一个问号,看来驱动出问题了,试着用原来的办法无法强行安装,出现如下报错: 主要原因是老旧的设备驱动程序没有及时更新,遭到了新系统的嫌弃,导致数字签名验证失败,…

golang for循环append的数据重复

原因,因为使用了& 需要增加一行,问题解决

华为云云耀云服务器L实例评测| 搭建属于自己的第一个中秋快乐网页

华为云服务器 1 如何快速获得一个华为云服务器1.1 注册华为云账号1.2 选择华为云服务器实例 (云耀L系列)1.3 选择服务器区域1.4 选择实例规格1.5 付款界面确认实例参数,支付即可 2 运行自己的服务器2.1 找到自己的服务器控制面板2.2 了解服务器面板2.3 登录我们的服…

【网络编程】TCP Socket编程

TCP Socket编程 1. ServerSocket2. Socket3. TCP的长短连接4. Socket 通信模型5. 代码示例:TCP 回显服务器 流套接字: 使用传输层TCP协议 TCP: 即Transmission Control Protocol(传输控制协议),传输层协议。 TCP的特点…

Pycharm配置环境以及Teminal不能使用问题解决

Pycharm配置环境 配置好环境后点击Terminal Teminal不能使用问题解决 我的报错信息: Import-Module : 无法加载文件 D:\Anaconda\shell\condabin\Conda.psm1,因为在此系统上禁止运行脚本。 解决方案: 第一步.:在 Windows 下用…

K8S名称空间和资源配额

Kubernetes 支持多个虚拟集群,底层依赖于同一个物理集群。 这些虚拟集群被称为名称空间。名称空间namespace是k8s集群级别的资源,可以给不同的用户、租户、环境或项目创建对应的名称空间,例如,可以为test、dev、prod环境分别创建各…

服务器搭建(TCP套接字)-基础版(服务端)

一、socket 1.1、vim man查看socket :!man socket1.2、 依赖的头文件 #include <sys/types.h> #include <sys/socket.h>1.3、原型 int socket(int domain, int type, int protocol);domain说明AF_INETIPV4协议AF_INET6IPV6协议AF_LOCALUnix域协议 type说明S…

JavaScript中的垃圾回收机制

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ JavaScript的垃圾回收机制⭐ 内存管理⭐ 引用计数⭐ 标记-清除算法⭐ 内存泄漏⭐ 性能优化⭐ 使用delete操作符⭐ 注意循环中的变量引用⭐ 使用工具进行内存分析⭐ 使用合适的数据结构⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探…

企业架构LNMP学习笔记54

企业架构NoSQL数据库之MongoDB。 学习目标和内容&#xff1a; 1&#xff09;能够简单描述mongoDB的使用特点&#xff1a; 2&#xff09;能够安装配置启动MongoDB&#xff1b; 3&#xff09;能够使用命令行客户端简单操作MongoDB&#xff1b; 4&#xff09;能够实现基本的数…

vsftp3.0 匿名用户,本地用户,虚拟用户

整体配置介绍&#xff1a; 进入vsftpd配置文件 vim /etc/vsftpd/vsftpd.conf //输入i开始编辑&#xff0c;修改后按esc退出编辑&#xff0c;输入:wq后回车保存并退出anonymous_enableYES #接受匿名用户&#xff0c;默认无密码请求 lo…

01_Elasticsearch入门介绍

01_Elasticsearch入门介绍 Elasticsearch 是什么1、什么是搜索&#xff1f;2、如果用数据库做搜索会怎么样&#xff1f;3、什么是全文检索和Lucene&#xff1f;4、什么是Elasticsearch&#xff1f;5、Elasticsearch的功能6、Elasticsearch的适用场景7、Elasticsearch的特点 什么…

Anaconda成功安装之后没有在菜单列和桌面显示图标

1、进入命令提示符 2、输入cmd 3、进入到Anaconda安装路径 比如我装在F盘 4、然后输入 python .\Lib\_nsis.py mkmenus 回车 这时候菜单列就可以看到了

第 4 章 串(串的堆分配存储实现)

1. 背景说明 实现基本与定长分配一致&#xff0c;不过将定长分配改为动态分配&#xff0c;解除了长度限制&#xff0c;实现更加灵活。 2. 示例代码 1) status.h /* DataStructure 预定义常量和类型头文件 */#ifndef STATUS_H #define STATUS_H#define CHECK_NULL(pointer) if …

[JAVAee]spring-Bean对象的执行流程与生命周期

执行流程 spring中Bean对象的执行流程大致分为四步: 启动Spring容器实例化Bean对象Bean对象注册到Spring容器中将Bean对象装配到所需的类中 ①启动Spring容器,在main方法中获取spring上下文对象并配备spring. import demo.*;import org.springframework.context.Applicati…