浅析PyTorch中nn.Linear的使用
更新时间:2019年08月18日 15:32:46 作者:Steven·简谈
这篇文章主要介绍了浅析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()
...
需要实现的内容:

计算步骤:
@weak_script_method
def forward(self, input):
return F.linear(input, self.weight, self.bias)
返回的是:input * weight + bias
对于 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}}`
对于 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}}`
实例展示
举个例子:
>>> 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
执行的操作是:
[140,100]×[100,50]=[140,50]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Python中 pickle 模块的 dump() 和 load()&
Python 的 pickle 模块用于实现二进制序列化和反序列化,一个对象可以被序列化到文件中,然后可以从文件中恢复,这篇文章主要介绍了Python中 pickle 模块的 dump() 和 load() 方法详解,需要的朋友可以参考下2022-12-12
详解Ubuntu16.04安装Python3.7及其pip3并切换为默认版本
这篇文章主要介绍了详解Ubuntu16.04安装Python3.7及其pip3并切换为默认版本,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-02-02
如何在Windows下载、安装Python和配置环境(新手、保姆级教程)
本文详细介绍了如何在Windows系统上下载、安装Python以及配置环境变量,通过步骤说明,即使是新手也能顺利完成Python的安装,并验证其是否成功,感兴趣的朋友跟随小编一起看看吧2024-11-11


最新评论