21.神经网络-线性层及其他层介绍

一、神经网络其他结构

1. 正则化层

神经网络中的正则化(Regularization)主要作用是‌防止模型过拟合(Overfitting),提高模型的泛化能力‌。

‌抑制过拟合‌:通过惩罚复杂的模型结构或过大的权重值,避免模型对训练数据中的噪声过度敏感。

‌提高泛化能力‌使模型在面对新数据时也能保持稳定的预测性能,缩小训练误差与测试误差之间的差距。

BatchNorm2d

BatchNorm2d-With Learnable Parameters

m = nn.BatchNorm2d(100)

BatchNorm2d-Without Learnable Parameters

m = nn.BatchNorm2d(100, affine=False)

input = torch.randn(20, 100, 35, 45)

output = m(input)

2.循环神经网络层(Recurrent)

包含RNN、LSTM等,适用于文字识别等序列任务

3.Dropout层

随机置零输入元素以防止过拟合

4.线性层(Linear)torch.nn.Linear

神经网络图示例

X1到Xd 的个数是in_features

out_features是g的个数,也就是L个。

关于是否有b,是根据torch.nn.Linear的参数bias是true还是false决定的。

weight是k,bias是b.

VGG16网络结构(线性层使用)

如上图,新绿色部分,是全连接层。

比如,我们有5 X 5 的图片,首先将其展平为1 X 25的,然后降低维度将25个变成3个。

将特征展平,可以使用flatten或者reshape.

1. 使用flatten

output = torch.flatten(images) # 自动展平

2. 使用reshape

output = torch.reshape(images, (1,1,1,-1)) # 显式指定形状

使用reshape展平代码示例
python 复制代码
# -*- coding: utf-8 -*-
# 作者:小土堆
# 公众号:土堆碎念
import torch
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader

dataset = torchvision.datasets.CIFAR10("../data", train=False, transform=torchvision.transforms.ToTensor(),
                                       download=True)

dataloader = DataLoader(dataset, batch_size=64, drop_last=True)

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.linear1 = Linear(196608, 10)

    def forward(self, input):
        output = self.linear1(input)
        return output

tudui = Tudui()

for data in dataloader:
    imgs, targets = data
    print(imgs.shape)
    output = torch.reshape(imgs,(1,1,1,-1))
    print(output.shape)
    output = tudui(output)
    print(output.shape)

torch.Size(64, 3, 32, 32)

torch.Size(1, 1, 1, 196608)

torch.Size(1, 1, 1, 10)

如上,注意,由于我们reshape展平操作后打印出来的图片的shape的宽度尺寸是196608,所以我们在调用线性函数的时候,传入的in_features参数是196608,因为我们希望维度降低到10,所以传入的out_features参数是10.

执行完成线性降低维度后,我们打印出来的输出图片的size就是10的宽度尺寸了。

通过reshape展平后,输出的是四维张量,四维张量的定义如下

使用flatten展平代码示例

flatten的示例使用如下:

python 复制代码
# -*- coding: utf-8 -*-
# 作者:小土堆
# 公众号:土堆碎念
import torch
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader

dataset = torchvision.datasets.CIFAR10("../data", train=False, transform=torchvision.transforms.ToTensor(),
                                       download=True)

dataloader = DataLoader(dataset, batch_size=64, drop_last=True)

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.linear1 = Linear(196608, 10)

    def forward(self, input):
        output = self.linear1(input)
        return output

tudui = Tudui()

for data in dataloader:
    imgs, targets = data
    print(imgs.shape)
    output = torch.flatten(imgs)
    print(output.shape)
    output = tudui(output)
    print(output.shape)

torch.Size(64, 3, 32, 32)

torch.Size(196608)

torch.Size(10)

我们发现使用flatten降低维度,与reshape输出的维度是4维的不同,flatten输出的图片的维度是1维的。

相关推荐
鱼宵1 小时前
Spring AI 初体验:配好 yml 就能聊,ChatClient 四步链式调用
人工智能·spring·microsoft·大模型·springai·chatclient
答案是你1 小时前
YOLOE 开放词汇检测 + ONNX / TensorRT 推理,开源了!
python·深度学习·yolo·目标检测·计算机视觉·视觉检测
朝朝辞暮i1 小时前
VLA 系统学习第 7 课:loss.backward() 到底做了什么?——从计算图到反向传播
人工智能·python·深度学习·神经网络·vla
serdes211 小时前
56G PAM4 SerDes RX MMCDR Mueller–Müller 误差检测与数据对齐设计
人工智能
倔强的石头1061 小时前
DeepSeek系列_国产大模型的技术创新解析
人工智能·大模型
企业数字化笔记1 小时前
AI工具的文件和参数怎么设计?上传校验、配置版本与可复现任务
前端·人工智能
seconp1 小时前
AI 时代怎么做计算机毕业设计?
人工智能·毕业设计·软件工程·课程设计·毕设
loulanyue_1 小时前
智能成为“商品”之后:读吴泳铭 2026 云栖演讲的六个取舍
人工智能