淺析PyTorch中nn.Linear的使用
查看源碼
Linear 的初始化部分:
class Linear(Module):
...
__constants__ = ['bias']
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()
...
需要實(shí)現(xiàn)的內(nèi)容:

計(jì)算步驟:
@weak_script_method
def forward(self, input):
return F.linear(input, self.weight, self.bias)
返回的是:input * weight + bias
對(duì)于 weight
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}}`
對(duì)于 bias
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}}`
實(shí)例展示
舉個(gè)例子:
>>> import torch >>> nn1 = torch.nn.Linear(100, 50) >>> input1 = torch.randn(140, 100) >>> output1 = nn1(input1) >>> output1.size() torch.Size([140, 50])
張量的大小由 140 x 100 變成了 140 x 50
執(zhí)行的操作是:
[140,100]×[100,50]=[140,50]
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python處理中文標(biāo)點(diǎn)符號(hào)大集合
中文文本中可能出現(xiàn)的標(biāo)點(diǎn)符號(hào)來(lái)源比較復(fù)雜,通過(guò)匹配等手段對(duì)他們處理的時(shí)候需要格外小心,防止遺漏,下面小編給大家?guī)?lái)了Python處理中文標(biāo)點(diǎn)符號(hào)大集合,感興趣的朋友跟隨腳本之家小編一起看看吧2018-05-05
解決Python保存文件名太長(zhǎng)OSError: [Errno 36] File
這篇文章主要介紹了解決Python保存文件名太長(zhǎng)OSError: [Errno 36] File name too lon問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python pyinstaller庫(kù)的安裝配置教程分享
pyinstaller模塊主要用于python代碼打包成exe程序直接使用,這樣在其它電腦上即使沒(méi)有python環(huán)境也是可以運(yùn)行的。本文就來(lái)和大家分享一下pyinstaller庫(kù)的安裝配置教程,希望對(duì)大家有所幫助2023-04-04
使用 tf.nn.dynamic_rnn 展開(kāi)時(shí)間維度方式
今天小編就為大家分享一篇使用 tf.nn.dynamic_rnn 展開(kāi)時(shí)間維度方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01
Python3 requests文件下載 期間顯示文件信息和下載進(jìn)度代碼實(shí)例
這篇文章主要介紹了Python3 requests文件下載 期間顯示文件信息和下載進(jìn)度代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Jupyter Notebook 如何修改字體和大小以及更改字體樣式
這篇文章主要介紹了Jupyter Notebook 如何修改字體和大小以及更改字體樣式的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Python3.5實(shí)現(xiàn)的羅馬數(shù)字轉(zhuǎn)換成整數(shù)功能示例
這篇文章主要介紹了Python3.5實(shí)現(xiàn)的羅馬數(shù)字轉(zhuǎn)換成整數(shù)功能,涉及Python字符串遍歷與數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2019-02-02
Python+Selenium實(shí)現(xiàn)讀取網(wǎng)易郵箱驗(yàn)證碼
在自動(dòng)化工作中,有可能會(huì)遇到一些發(fā)送郵箱驗(yàn)證碼類(lèi)似的功能。本文將利用Python?Selenium實(shí)現(xiàn)自動(dòng)化讀取網(wǎng)易郵箱驗(yàn)證碼,感興趣的可以了解一下2022-03-03

