【Pytorch基础】torch.nn.Linear()函数

本文详细介绍了PyTorch中的全连接层nn.Linear(),通过实例展示了如何使用该层进行线性变换,并解释了m.weight.shape为何为(30,20),即权重矩阵的设置方式。nn.Linear()用于网络中构建从20维到30维的转换,通过权重矩阵的转置与输入数据相乘再加上偏置项完成计算。内容涵盖了线性变换的数学原理和PyTorch实现的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PyTorch的nn.Linear()是用于设置网络中的全连接层具体的介绍如下:

import torch

x = torch.randn(128, 20)  # 输入的维度是(128,20)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)
print('m.weight.shape:\n ', m.weight.shape)
m.weight.shape:
  torch.Size([30, 20])
  
print('m.bias.shape:\n', m.bias.shape)
m.bias.shape:
 torch.Size([30])
 
print('output.shape:\n', output.shape)
output.shape:
 torch.Size([128, 30])
 
# ans = torch.mm(input,torch.t(m.weight))+m.bias 等价于下面的
ans = torch.mm(x, m.weight.t()) + m.bias   
print('ans.shape:\n', ans.shape)
ans.shape:
 torch.Size([128, 30])
 
print(torch.equal(ans, output))
True

为什么   m . w e i g h t . s h a p e = ( 30 , 20 )   ? \rm{} ~m.weight.shape = (30,20)~?  m.weight.shape=(30,20) ?
答:因为线性变换的公式是:
y = x A T + b y = x A ^T + b y=xAT+b

先生成一个(30,20)的weight,实际运算中再转置,这样就能和x做矩阵乘法了

参考文献

[1]torch.nn.Linear() 理解
[2]PyTorch的nn.Linear()详解
[3]https://pytorch.org/docs/master/nn.html#linear-layers

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值