线性层(全连接层)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) ```

相关推荐
张较瘦_1 小时前
[论文阅读] 人工智能 + 软件工程 | 需求获取访谈中LLM生成跟进问题研究:来龙去脉与创新突破
论文阅读·人工智能
一 铭2 小时前
AI领域新趋势:从提示(Prompt)工程到上下文(Context)工程
人工智能·语言模型·大模型·llm·prompt
麻雀无能为力5 小时前
CAU数据挖掘实验 表分析数据插件
人工智能·数据挖掘·中国农业大学
时序之心5 小时前
时空数据挖掘五大革新方向详解篇!
人工智能·数据挖掘·论文·时间序列
.30-06Springfield6 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
说私域7 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
永洪科技7 小时前
永洪科技荣获商业智能品牌影响力奖,全力打造”AI+决策”引擎
大数据·人工智能·科技·数据分析·数据可视化·bi
shangyingying_17 小时前
关于小波降噪、小波增强、小波去雾的原理区分
人工智能·深度学习·计算机视觉
书玮嘎8 小时前
【WIP】【VLA&VLM——InternVL系列】
人工智能·深度学习
猫头虎8 小时前
猫头虎 AI工具分享:一个网页抓取、结构化数据提取、网页爬取、浏览器自动化操作工具:Hyperbrowser MCP
运维·人工智能·gpt·开源·自动化·文心一言·ai编程