线性层(全连接层)pytorch

**前置知识:

1、线性层和非线性激活函数:

组合使用:通常,线性层后面会接一个非线性激活函数。这样,网络先做一次简单的转换(线性),然后用激活函数(非线性)添加一些复杂性。

(即 output = activation(linear(input)) )

2、

  • 线性层:执行线性变换。
  • 全连接层:是一种特殊的线性层,所有输入节点与所有输出节点相连。

在实践中,两者常常被视作同义词。

3、linear_layer = nn.Linear(4, 2)

  • 输入特征数量:in_features (int) -- size of each input sample

  • 输出特征数量:out_features (int) -- size of each output sample

  • 偏置:bias (bool) -- If set to False, the layer will not learn an additive bias. Default: True

(默认True,自动学习并添加偏置参数)

4、

python 复制代码
import torch
from torch import nn

# 创建一个线性层,输入特征为 4,输出特征为 2
linear_layer = nn.Linear(4, 2)

# 创建一个示例输入,batch_size 为 3
input_tensor = torch.tensor([[1.0, 2.0, 3.0, 4.0],
                              [5.0, 6.0, 7.0, 8.0],
                              [9.0, 10.0, 11.0, 12.0]])

# 前向传播
output_tensor = linear_layer(input_tensor)

# 打印输出
print("Output Tensor:")
print(output_tensor)

#tensor([[ 1.3422, -1.4755],
#        [ 2.4565, -2.6873],
#        [ 3.5708, -3.8991]], grad_fn=<AddmmBackward0>)

这里,input_tensor形状为(3,4),意味着有3个样本(batch_size),每个样本有4个特征

(输入张量的每一列通常代表一个特征)

output_tensor形状为(3,4),意味着还是3个样本,但是特征数变成了2

5、具体如何计算,将 4 个输入特征转换为 2 个输出特征:

经过这样的计算,输入的 4 个特征被转换为 2 个特征,得到的输出张量将是:

output = [[3.1, 7.2], # 第一个样本的输出

...\], # 第二个样本的输出 \[...\]\] # 第三个样本的输出 6、关于权重和偏置: 在 PyTorch 中,线性层的权重矩阵 W 和偏置 b 是在模型创建时自动初始化的。 这些参数的具体值是在模型训练之前随机生成的,通常使用某种分布(如均匀分布或正态分布)进行初始化。 在训练过程中,权重和偏置会自动调整。(向前传播------计算损失------反向传播------更新参数) ## \*\*代码: ```python import torch import torchvision.datasets from torch import nn from torch.nn import Linear from torch.utils.data import DataLoader test_set=torchvision.datasets.CIFAR10(root="./dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True) dataloader=DataLoader(test_set,batch_size=64,drop_last=True) class Xigua(nn.Module): def __init__(self): super().__init__() self.linear1=Linear(196608,10) def forward(self,input): output=self.linear1(input) return output xigua1=Xigua() for data in dataloader: imgs,targets=data #torch.Size([64, 3, 32, 32]) # input=torch.reshape(imgs,(1,1,1,-1))#torch.Size([1, 1, 1, 196608]) input=torch.flatten(imgs) #flatten展开成一行(仅一维) print(input.shape) output=xigua1(input) print(output) ```

相关推荐
萧鼎22 分钟前
RAGFlow:构建高效检索增强生成流程的技术解析
人工智能·python
爱的叹息26 分钟前
主流开源 LLM 应用开发平台详解
人工智能·开源
赋范大模型技术社区28 分钟前
从0手撕代码搭建MCP Client与Server!详解DeepSeek、ollama、vLLM接入MCP实战!
人工智能·mcp
Baihai_IDP37 分钟前
面对开源大模型浪潮,基础模型公司如何持续盈利?
人工智能·openai·deepseek
陈明勇39 分钟前
MCP 实战:用 Go 语言开发一个查询 IP 信息的 MCP 服务器
人工智能·后端·mcp
浏览器爱好者44 分钟前
如何下载适用于语音识别功能增强的Google Chrome浏览器
人工智能·chrome·语音识别
孔令飞1 小时前
彻底学会 gRPC:用 Go 实现一个迷你考试服务
人工智能·云原生·go
梓羽玩Python1 小时前
告别OCR!这个AI文档神器直接"看懂"PDF,支持文档归类及多模态问答!
人工智能·github
weixin_457885821 小时前
Discuz!+DeepSeek:传统论坛的智能化蜕变之路
人工智能·学习·discuz·deepseek
檀越剑指大厂2 小时前
Browser-Use WebUI:让AI自动使用浏览器帮你查询信息执行任务
人工智能