pytorch——nn.Linear()

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

nn.Linear(n,s)。——>与输入相乘的权重矩阵(A^T)的形状:n*s。

nn.Linear层的输入的形状是:m*n。

nn.Linear层的输出就是m*s。

 

 

 

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
PyTorch中进行二分类可以使用交叉熵损失函数和Adam梯度优化器。首先,可以定义一个自定义的神经网络类,继承自nn.Module,并在其中定义网络结构。例如,在网络中可以使用nn.Linear来定义输入层和隐藏层之间的全连接层,然后使用nn.Sigmoid或者nn.ReLU等非线性激活函数。接着,在forward方法中定义网络的前向传播过程。最后,可以在predict方法中使用softmax函数将输出转换为概率,并根据阈值将概率转换为预测结果。以下是一个简单的例子: ```python import torch import torch.nn as nn import torch.nn.functional as F class MyClassifier(nn.Module): def __init__(self): super(MyClassifier, self).__init__() self.fc1 = nn.Linear(2, 3) self.fc2 = nn.Linear(3, 2) def forward(self, x): x = self.fc1(x) x = F.tanh(x) x = self.fc2(x) return x def predict(self, x): pred = F.softmax(self.forward(x)) ans = [] for t in pred: if t > t123 #### 引用[.reference_title] - *1* *3* [Pytorch实现二分类器](https://blog.csdn.net/lizzy05/article/details/90521909)[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^v92^chatsearchT0_1"}} ] [.reference_item] - *2* [PyTorch深度学习——Logistic回归(二分类问题)](https://blog.csdn.net/weixin_42603976/article/details/126171385)[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^v92^chatsearchT0_1"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值