18-神经网络-自定义带参数的层
1、nn.Parameter函数
2、torch.mm 和torch.matmul区别
都是 PyTorch 中用于矩阵乘法的函数,但它们在使用上有细微的差别
import torch import torch.nn as nn import torch.nn.functional as F class MyLinear(nn.Module): def __init__(self, in_units, out_units): super(MyLinear, self).__init__() self.weight = nn.Parameter(torch.randn((in_units, out_units))) self.bias = nn.Parameter(torch.randn(out_units)) def forward(self, x): linear = torch.matmul(x, self.weight) + self.bias return F.relu(linear) linear = MyLinear(5, 3) print(linear.weight) y = linear(torch.rand((2, 5))) print(y)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步