torch.nn.Linear()函数

torch.nn.Linear(in_features, out_features, bias=True) 函数是一个线性变换函数:
在这里插入图片描述

其中,in_features为输入样本的大小,out_features为输出样本的大小,bias默认为true。如果设置bias = false那么该层将不会学习一个加性偏差。

Linear()函数通常用于设置网络中的全连接层。

import torch

x = torch.randn(8, 3)  # 输入样本
fc = torch.nn.Linear(3, 5)  # 20为输入样本大小,30为输出样本大小
output = fc(x)
print('fc.weight.shape:\n ', fc.weight.shape, fc.weight)
print('fc.bias.shape:\n', fc.bias.shape)
print('output.shape:\n', output.shape)

ans = torch.mm(x, torch.t(fc.weight)) + fc.bias  # 计算结果与fc(x)相同
print('ans.shape:\n', ans.shape)

print(torch.equal(ans, output))

输出结果为:

fc.weight.shape:
  torch.Size([5, 3]) Parameter containing:
tensor([[-0.1878, -0.2082,  0.4506],
        [ 0.3230,  0.3543,  0.3187],
        [-0.0993, -0.0028, -0.1001],
        [-0.0479,  0.3248, -0.4867],
        [ 0.0574,  0.0451,  0.1525]], requires_grad=True)
fc.bias.shape:
 torch.Size([5])
output.shape:
 torch.Size([8, 5])
ans.shape:
 torch.Size([8, 5])
True

Process finished with exit code 0

首先,nn.linear(3,5)其权重的shape为(5,3),所以x与其相乘时,用torch.t求了nn.linear的转置,这样(83)(35)得到全连接层后的输出维度(85),结果也与fc(x)验证是一致的, torch.mm就是数学上的两个矩阵 相乘。

参考文献:
https://blog.csdn.net/daodaipsrensheng/article/details/117259324

  • 7
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
torch.nn.Linear函数PyTorch中的一个线性变换函数。它接受三个参数:in_features表示输入的特征数,out_features表示输出的特征数,bias是一个布尔值,表示是否使用偏置项。该函数将输入特征与权重矩阵相乘,并可选择是否加上偏置项,从而进行线性变换。 在nn.Linear函数中,权重矩阵的形状是(out_features, in_features),而输入特征的形状是(batch_size, in_features)。当输入特征与权重矩阵相乘时,可以使用torch.t对nn.Linear的权重矩阵进行转置,以便进行矩阵乘法操作。这样得到的输出维度将是(batch_size, out_features)。torch.mm函数可以用来执行矩阵相乘的操作。 因此,torch.nn.Linear函数可以用来构建神经网络的全连接层,将输入特征与权重矩阵相乘,并添加偏置项,得到线性变换后的输出。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [torch.nn.Linear()函数](https://blog.csdn.net/qq_35037684/article/details/121624295)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [【Pytorch基础】torch.nn.Linear()函数](https://blog.csdn.net/zfhsfdhdfajhsr/article/details/115228920)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一位不愿暴露自己的小可爱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值