10.09学习笔记(卷积神经网络pytorch)

torch.nn

卷积层的学习(pytorch版本)


import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10(root="../dataset", train=False, transform=torchvision.transforms.ToTensor(), download=True)
dataloader = DataLoader(dataset, batch_size=64)

class Myconv(nn.Module):
    def __init__(self):
        super(Myconv, self).__init__()
        self.conv1 = torch.nn.Conv2d(3, 6, kernel_size=3, padding=0)

    def forward(self, x):
       x = self.conv1(x)
       return x

myconv = Myconv()

writer = SummaryWriter("torch_logs")
step = 0

for data in dataloader:
    imgs, target = data
    output = myconv(imgs)
    print(imgs.shape)
    print(output.shape)
    writer.add_images("input", imgs, step)
    output = torch.reshape(output, (-1, 3, 30, 30))
    writer.add_images("output", output, step)
    step += 1
    
writer.close()

卷积前:

在这里插入图片描述

卷积后(reshape):

在这里插入图片描述

卷积后(选择前面三个通道)
output = torch.sigmoid(output)
writer.add_images("output", output[:, :3, :, :], step) # 选择前面的三个通道

在这里插入图片描述

VGG-16 | CNN model

来自:https://www.geeksforgeeks.org/vgg-16-cnn-model/

卷积图

  • Input Layer:

Input dimensions: (224, 224, 3)

  • Convolutional Layers (64 filters, 3×3 filters, same padding):

Two consecutive convolutional layers with 64 filters each and a filter size of 3×3.

Same padding is applied to maintain spatial dimensions.

  • Max Pooling Layer (2×2, stride 2):

Max-pooling layer with a pool size of 2×2 and a stride of 2

  • Convolutional Layers (128 filters, 3×3 filters, same padding):

Two consecutive convolutional layers with 128 filters each and a filter size of 3×3.

  • Max Pooling Layer (2×2, stride 2):

Max-pooling layer with a pool size of 2×2 and a stride of 2.

  • Convolutional Layers (256 filters, 3×3 filters, same padding):

Two consecutive convolutional layers with 256 filters each and a filter size of 3×3.

  • Convolutional Layers (512 filters, 3×3 filters, same padding):

Two sets of three consecutive convolutional layers with 512 filters each and a filter size of 3×3.

  • Max Pooling Layer (2×2, stride 2):

Max-pooling layer with a pool size of 2×2 and a stride of 2.

  • Stack of Convolutional Layers and Max Pooling:

Two additional convolutional layers after the previous stack. Filter size: 3×3.

  • Flattening:

Flatten the output feature map (7x7x512) into a vector of size 25088.

  • Fully Connected Layers:

Three fully connected layers with ReLU activation.

First layer with input size 25088 and output size 4096.

Second layer with input size 4096 and output size 4096.

Third layer with input size 4096 and output size 1000, corresponding to the 1000 classes in the ILSVRC challenge.

Softmax activation is applied to the output of the third fully connected layer for classification.

MaxPooling

Maxpooling(最大池化)是一种常用的下采样(subsampling)或降维操作,通常在卷积神经网络(CNN)中用于减小特征图的尺寸,同时保留重要信息。它通过在输入特征图的局部窗口内取最大值,减少特征图的空间维度,且不会显著损失重要特征。

工作原理:
  • Maxpooling的操作通常通过滑动窗口在特征图上移动,每个窗口覆盖一小块区域,并在该区域内选取最大值作为输出。

  • 例如,常见的2x2 Maxpooling会将2x2的区域中的最大值作为新的特征,输出尺寸会减小到原来的1/4。

 4x4 特征图
[[1, 3, 2, 0],
 [4, 6, 1, 2],
 [7, 5, 3, 1],
 [0, 2, 9, 8]]

Maxpooling之后

 2x2 Maxpooling,滑动窗口为 2x2,步幅为 2
 [[6, 2],
 [7, 9]]
作用:
  1. 下采样:通过降低特征图的空间维度,减少数据量,使得模型可以在不增加太多计算开销的情况下更高效地处理数据。

  2. 增强鲁棒性:由于池化操作只保留局部区域中的最大值,即使输入图像有少量的平移或旋转,模型仍然可以保持相对不变性,增强模型对输入数据的鲁棒性。

  3. 防止过拟合:Maxpooling通过简化特征表示,减少了模型过拟合到训练数据上不重要的噪声或细节的可能性。

代码:
import torch
import torchvision
from torch import nn
from torch.nn import MaxPool2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

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

dataloader = DataLoader(dataset, batch_size=64)

class MyNN(nn.Module):
    def __init__(self):
        super(MyNN, self).__init__()
        self.maxpool2d = MaxPool2d(kernel_size=3, ceil_mode=False)

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

mynn = MyNN()

writer = SummaryWriter("maxpool_torch")
step = 0
for data in dataloader:
    imgs, target = data
    writer.add_images("input", imgs, step)
    output = mynn(imgs)
    writer.add_images("output", output, step)
    step += 1

writer.close()


池化前:

在这里插入图片描述

池化后:

池化的本质是对图像进行下采样(如Max Pooling或Average Pooling),以减少数据维度和计算量。在这个过程中,某些像素信息会被丢弃或简化,这导致图像的细节被压缩,从而变得模糊。

在这里插入图片描述

非线性激活

非线性激活函数是深度神经网络中的重要组件,它们引入非线性,使得网络能够处理更复杂的模式和特征。没有非线性激活,神经网络的层与层之间的映射将是线性的,这样的网络无论有多少层,其效果等同于单层线性模型。因此,非线性激活函数是构建深层神经网络的关键。

1. ReLU (Rectified Linear Unit)

  • 公式: ( f(x) = max(0, x) )
  • 优点:计算简单、导数为常数,有效缓解梯度消失问题,常被用于大多数现代神经网络中。
  • 缺点:在训练过程中,如果输入是负数,ReLU 的导数为 0,可能导致“死亡”神经元(即权重无法更新,单元永远不会激活)。

2. Sigmoid

  • 公式: ( f(x) = \frac {1}{1 + e^{-x}} )
  • 优点:输出值在 ( (0, 1) ) 之间,常用于二分类问题的输出层。
  • 缺点:容易出现梯度消失问题,导致深层网络训练较慢,且输出不为 0 的值时会导致梯度减小。
代码:

dataset = torchvision.datasets.CIFAR10(root="../dataset", train=False, transform=torchvision.transforms.ToTensor(), download=True)
dataloader = DataLoader(dataset,batch_size=64)

class myRelu(nn.Module):

    def __init__(self):
        super(myRelu, self).__init__()
        self.relu = ReLU()
        self.sigmoid = Sigmoid()

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

writer = SummaryWriter("torch_relu")
myrelu = myRelu()

step = 0
for data in dataloader:
    imgs,target = data
    writer.add_images("input", imgs, step)
    output = myrelu(imgs)
    writer.add_images("output", output, step)
    step += 1

writer.close()

Flatten 和 Linear

Flatten 的作用是将多维数据转换为一维向量,以便在后续的全连接层中进行处理。在卷积神经网络的前几层,卷积层和池化层会对输入的图像进行操作,保持其二维甚至三维结构(如图像的高度、宽度、通道数)。但在最终的分类阶段,我们通常需要将这些高维数据输入到全连接层中,而全连接层只能处理一维输入。

Linear 是一个线性变换层,通常称为全连接层(Fully Connected Layer,FC)。它的作用是将输入的每个节点与输出的每个节点进行线性组合,并通过权重和偏置计算输出。全连接层常用于网络的最后几层,用来进行分类或回归任务。

代码:
dataset = torchvision.datasets.CIFAR10(root="../dataset", train=False, transform=torchvision.transforms.ToTensor(), download=True)
dataloader = DataLoader(dataset, batch_size=64)

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

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


mylinear = Mylinear()
writer = SummaryWriter("torch_linear")

step = 0
for data in dataloader:
    imgs, target = data
    print(imgs.shape)
    writer.add_images("input", imgs, step)
    output = torch.flatten(imgs)
    print(output.shape)
    output = mylinear(output)
    print(output.shape)
    writer.add_images("output", output, step)
    step += 1

writer.close()
输出:
torch.Size([64, 3, 32, 32])
torch.Size([196608])
torch.Size([10])
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值