最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Pytorch中的torch.nn.Linear()方法用法解讀

 更新時(shí)間:2024年02月26日 10:09:14   作者:擁抱晨曦之溫暖  
這篇文章主要介紹了Pytorch中的torch.nn.Linear()方法用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Pytorch torch.nn.Linear()方法

torch.nn.Linear()作為深度學(xué)習(xí)中最簡(jiǎn)單的線性變換方法,其主要作用是對(duì)輸入數(shù)據(jù)應(yīng)用線性轉(zhuǎn)換

看一下官方的解釋及介紹

class Linear(Module):
    r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
    This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
    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']
    in_features: int
    out_features: int
    weight: Tensor
 
    def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
        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) -> None:
        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: Tensor) -> Tensor:
        return F.linear(input, self.weight, self.bias)
 
    def extra_repr(self) -> str:
        return 'in_features={}, out_features={}, bias={}'.format(
            self.in_features, self.out_features, self.bias is not None
        )
 
 
# This class exists solely for Transformer; it has an annotation stating
# that bias is never None, which appeases TorchScript

這里我們主要看__init__()方法,很容易知道,當(dāng)我們使用這個(gè)方法時(shí)一般需要傳入2~3個(gè)參數(shù),分別是in_features: int, out_features: int, bias: bool = True,第三個(gè)參數(shù)是說是否加偏置(bias),簡(jiǎn)單來講,這個(gè)函數(shù)其實(shí)就是一個(gè)'一次函數(shù)':y = xA^T + b,(T表示張量A的轉(zhuǎn)置),首先super(Linear, self).__init__()就是老生常談的方法,之后初始化in_features和out_features,接下來就是比較重要的weight的設(shè)置,我們可以很清晰的看到weight的shape是(out_features,in_features)的,而我們?cè)谧鰔A^T時(shí),并不是x和A^T相乘的,而是x和A.weight^T相乘的,這里需要大大留意,也就是說先對(duì)A做轉(zhuǎn)置得到A.weight,然后在丟入y = xA^T + b中,得出結(jié)果。

接下來奉上一個(gè)小例子來實(shí)踐一下:

import torch
 
# 隨機(jī)初始化一個(gè)shape為(128,20)的Tensor
x = torch.randn(128,20)
# 構(gòu)造線性變換函數(shù)y = xA^T + b,且參數(shù)(20,30)指的是A的shape,則A.weight的shape就是(30,20)了
y= torch.nn.Linear(20,30)
output = y(x)
# 按照以上邏輯使用torch中的簡(jiǎn)單乘法函數(shù)進(jìn)行檢驗(yàn),結(jié)果很顯然與上述符合
# 下面的y.weight可以理解為一個(gè)shape為(30,20)的一個(gè)可學(xué)習(xí)的矩陣,.t()表示轉(zhuǎn)置
# y.bias若為TRUE,則bias是一個(gè)Tensor,且其shape為out_features,在該程序中應(yīng)為30
# 更加細(xì)致的表達(dá)一下y = (128 * 20) * (30 * 20)^T + (if bias (1,30) ,else: 0)
ans = torch.mm(x,y.weight.t())+y.bias
print('ans.shape:\n',ans.shape)
print(torch.equal(ans,output))

對(duì)torch.nn.Linear的理解

torch.nn.Linear是pytorch的線性變換層

定義如下:

Linear(in_features: int, out_features: int, bias: bool = True, device: Any | None = None, dtype: Any | None = None)

全連接層 Fully Connect 一般就就用這個(gè)函數(shù)來實(shí)現(xiàn)。

因此在潛意識(shí)里,變換的輸入張量的 shape 為 (batchsize, in_features),輸出張量的 shape 為 (batchsize, out_features)。

當(dāng)然這是常用的方式,但是 Linear 的輸入張量的維度其實(shí)并不需要必須為上述的二維,多維也是完全可以的,Linear 僅是對(duì)輸入的最后一維做線性變換,不影響其他維。

可以看下官網(wǎng)的解釋

Linear — PyTorch 1.11.0 documentation

一個(gè)例子

如下:

import torch
input = torch.randn(30, 20, 10)  # [30, 20, 10]
linear = torch.nn.Linear(10, 15)  # (*, 10) --> (*, 15)
output = linear(input)
print(output.size()) # 輸出 [30, 20, 15]

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 用PyInstaller把Python代碼打包成單個(gè)獨(dú)立的exe可執(zhí)行文件

    用PyInstaller把Python代碼打包成單個(gè)獨(dú)立的exe可執(zhí)行文件

    這篇文章主要介紹了用PyInstaller把Python代碼打包成單個(gè)獨(dú)立的exe可執(zhí)行文件,需要的朋友可以參考下
    2018-05-05
  • python基礎(chǔ)中的文件對(duì)象詳解

    python基礎(chǔ)中的文件對(duì)象詳解

    這篇文章主要為大家介紹了python基礎(chǔ)中的文件對(duì)象,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01
  • python 提取html文本的方法

    python 提取html文本的方法

    在解決自然語言處理問題時(shí),有時(shí)你需要獲得大量的文本集?;ヂ?lián)網(wǎng)是文本的最大來源,但是從任意HTML頁面提取文本是一項(xiàng)艱巨而痛苦的任務(wù)。本文將講述python高效提取html文本的方法
    2021-05-05
  • Python使用RPC例子

    Python使用RPC例子

    本文主要介紹了Python使用RPC例子,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • Python 在OpenCV里實(shí)現(xiàn)仿射變換—坐標(biāo)變換效果

    Python 在OpenCV里實(shí)現(xiàn)仿射變換—坐標(biāo)變換效果

    這篇文章主要介紹了Python 在OpenCV里實(shí)現(xiàn)仿射變換—坐標(biāo)變換效果,本文通過一個(gè)例子給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-08-08
  • 使用Python Tkinter創(chuàng)建一個(gè)動(dòng)態(tài)祝福彈窗的詳細(xì)教程

    使用Python Tkinter創(chuàng)建一個(gè)動(dòng)態(tài)祝福彈窗的詳細(xì)教程

    本文手把手教你用Python的Tkinter庫創(chuàng)建一個(gè)浪漫的彈窗程序,包含淡入淡出動(dòng)畫、多線程管理、隊(duì)列控制等高級(jí)特性,通過完整的代碼解析和配置指南,帶你掌握GUI編程的核心技巧,需要的朋友可以參考下
    2025-11-11
  • Python中__init__方法使用的深度解析

    Python中__init__方法使用的深度解析

    在Python的面向?qū)ο缶幊蹋∣OP)體系中,__init__方法如同建造房屋時(shí)的"奠基儀式"——它定義了對(duì)象誕生時(shí)的初始狀態(tài),下面我們就來深入了解下__init__方法吧
    2025-04-04
  • python使用正則篩選信用卡

    python使用正則篩選信用卡

    這篇文章主要為大家詳細(xì)介紹了python使用正則篩選信用卡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • 淺談django2.0 ForeignKey參數(shù)的變化

    淺談django2.0 ForeignKey參數(shù)的變化

    今天小編就為大家分享一篇淺談django2.0 ForeignKey參數(shù)的變化,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Python+Kepler.gl實(shí)現(xiàn)時(shí)間輪播地圖過程解析

    Python+Kepler.gl實(shí)現(xiàn)時(shí)間輪播地圖過程解析

    這篇文章主要介紹了Python+Kepler.gl實(shí)現(xiàn)時(shí)間輪播地圖過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07

最新評(píng)論

杭锦旗| 保亭| 互助| 红安县| 喀喇沁旗| 广水市| 万州区| 靖宇县| 满城县| 甘南县| 宝山区| 霍林郭勒市| 内乡县| 灵璧县| 阿巴嘎旗| 桃园县| 玉溪市| 舞钢市| 耒阳市| 巴彦县| 台东县| 措美县| 庄浪县| 扶绥县| 五常市| 东兰县| 澜沧| 清丰县| 左权县| 武汉市| 宁蒗| 华容县| 南投市| 宿州市| 天全县| 台中县| 博爱县| 凤冈县| 保定市| 宜兴市| 崇仁县|