torch.nn.Linear()函数理解

本文详细解析了PyTorch中Linear层的工作原理,包括其参数设置、权重和偏置的作用,以及如何通过实例演示Linear层的前向传播过程。
部署运行你感兴趣的模型镜像

函数:class torch.nn.Linear(in_features,out_features,bias = True)

源码

从init函数中可以看出Linear中包含四个属性:

1)in_features: 上层神经元个数【每个输入样本的大小】

2)out_features: 本层神经元个数【每个输出样本的大小】

3)weight:权重,形状[out_features , in_features]

4)bias: 偏置,形状[out_features]。网络层是否有偏置,默认存在,且维度为[out_features ];若bias=False,则该网络层无偏置,图层不会学习附加偏差

 

示例说明

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)

print('m.bias.shape:\n', m.bias.shape)

print('output.shape:\n', output.shape)

 

# 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)

print(torch.equal(ans, output))

 

输出:

m.weight.shape:

    torch.Size([30, 20])

m.bias.shape:

    torch.Size([30])

output.shape:

    torch.Size([128, 30])

ans.shape:

    torch.Size([128, 30])

True

output.size()=矩阵size(128,20)*矩阵size(20,30)=(128,30)。

您可能感兴趣的与本文相关的镜像

PyTorch 2.8

PyTorch 2.8

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值