PyTorch深度学习实践【刘二大人】之卷积神经网络

视频地址10.卷积神经网络(基础篇)_哔哩哔哩_bilibili

网络中全部用的线形层串行连接起来,我们叫做全连接网络。输入与输出任意两节点间都有权重,这样的线形层叫做全连接层

卷积神经网络的基本特征,先特征提取再进行分类

3通道的图像,与3个卷积核做内积得到3个新的3*3矩阵,并对应位置相加

python 复制代码
import torch
import torch
from torchvision import transforms  # 处理数据的一个工具
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F  # 激活函数使用relu
import torch.optim as optim  # 优化器

batch_size = 64
transform = transforms.Compose([
    transforms.ToTensor(),  # 先把图像转化为c*w*h的张量
    transforms.Normalize((0.1307,), (0.3081,))  # 归一化,里面分别是均值,标准差,把0~255的像素转化为0~1
])

train_dataset = datasets.MNIST(root='../dataset/mnist/', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)

test_dataset = datasets.MNIST(root='../dataset/mnist/', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)


class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.convl = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.pooling = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(320, 10)

    def forward(self, x):
        # Flatten data from (n, 1, 28, 28) to (n, 784)
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(x)))
        x = x.view(batch_size, -1)  # flatten
        x = self.fc(x)
        return x


model = Net()
device = torch.device("cuda:O" if torch.cuda.is_available() else "cpu")
model.to(device)  # 将所有模块的参数和缓冲区转换为CUDA张量。
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)  # 冲量设置为0.5来优化训练过程


def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        inputs, target = inputs.to(device), target.to(device)  # 将每一步的输入和目标发送给GPU。
        optimizer.zero_grad()

        # forward + backward + update
        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()  # 用item避免构建计算图
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %ds. 3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
            running_loss = 0.0


def test():
    correct = 0
    total = 0
    with torch.no_grad():  # 不需要计算梯度
        for data in test_loader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)  # 寻找以第一维度的每行最大值,以及最大值下标
            total += labels.size(0)  # 加上这个批量的总数
            correct += (predicted == labels).sum().item()  # 计算预测对的数量
            print('Accuracy on test set: %d %%' % (100 * correct / total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

GoogLeNet的Inception模块,思路就是我们不知道多大的卷积核更好,我们就多选择几种卷积核然后concatenate进行沿通道拼接。

下面是此模型的主要代码

python 复制代码
import torch
from torch import nn
import torch.nn.functional as F


class InceptionA(nn.Module):
    def __init__(self, in_channels):
        super(InceptionA, self).__init__()
        self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1)
        self.branch5x5_1nn.Conv2d(in_channels, 16, kernel_size=1)
        self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2)
        self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
        self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1)
        self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1)
        self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)

    def forward(self, x):
        branch1x1 = self.branchlx1(x)
        branch5x5 = self.branch5x5_1(x)
        branch5x5 = self.branch5x5_2(branch5x5)
        branch3x3 = self.branch3x3_1(x)
        branch3x3 = self.branch3x3_2(branch3x3)
        branch3x3 = self.branch3x3_3(branch3x3)
        branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool = self.branch_pool(branch_pool)
        outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
        return torch.cat(outputs, dim=1)


class Net(nn.Module):
    def __init_(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(88, 20, kernel_size=5)
        self.incep1 = InceptionA(in_channels=10)
        self.incep2 = InceptionA(in_channels=20)
        self.mp = nn.MaxPool2d(2)
        self.fc = nn.Linear(1408, 10)

    def forward(self, x):
        in_size = x.size(0)
        x = F.relu(self.mp(self.conv1(x)))
        x = self.incep1(x)
        x = F.relu(self.mp(self.conv2(x)))
        x = self.incep2(x)
        x = x.view(in_size, -1)
        x = self.fc(x)
        return x

在卷积层数过多时,会出现梯度消失的情况,需要用残差网络来解决这个问题

python 复制代码
class ResidualBlock(nn.Module):
    def __init__(self, channels):
        super(ResidualBlock, self).__init__()
        self.channels = channels
        self.convl = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)

    def forward(self, x):
        y = F.relu(self.conv1(x))
        y = self.conv2(y)
        return F.relu(x + y) #把计算值y和原始值x相加
相关推荐
Web3&Basketball1 分钟前
从0到1落地Claude Playwright浏览器自动化Agent:踩坑全记录
深度学习·大模型·ai技术
Rocky Ding*6 分钟前
【三年面试五年模拟】2026-08-16_拼多多_笔试题与题解全解析
论文阅读·人工智能·深度学习·机器学习·aigc·ai-native·拼多多
leoZ2312 小时前
AI+前端提效-08 AI自动化文档:前端组件、接口、项目文档自动生成
前端·人工智能·深度学习·神经网络·目标检测·自然语言处理·自动化
️学习的小王2 小时前
AI Agent Skills实战教程:从原理到上手编写SKILL.md
人工智能·深度学习·学习·机器学习
萝萝仔2 小时前
02.人工智能训练师三级是什么?谁适合考?考了有什么用?
人工智能·深度学习·机器学习·ai·云计算
YOLO数据集集合3 小时前
蚊子视觉验证数据集 | 蚊虫识别 疟疾防控 病媒生物 细粒度分类 YOLO格式 深度学习数据集
深度学习·yolo·分类·数据集·蚊子分类·蚊虫分类·蚊虫识别
zx_741484814 小时前
【深度学习入门】Windows 下 PyTorch GPU 环境搭建
pytorch·windows·深度学习
CIO_Alliance4 小时前
AI提示系列(2)| Few-shot与ReAct有何不同? 大模型工具调用的底层逻辑详解
前端·人工智能·深度学习·神经网络·react.js·前端框架·ai+ipaas
牧羊人.3334 小时前
动手学深度学习 01:核心组件与完整训练流程
开发语言·人工智能·深度学习
吾在学习路4 小时前
XSKILL: Continual Learning from Experience and Skills in Multimodal Agents
人工智能·深度学习·机器学习