pytorch 实现VGG16 解决VGG误差不更新问题

问题

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
查看非叶子结点的梯度,不是none,如果把全连接层的激活函数删掉,结果一样,显然是激活函数的原因,因为loaddata函数
在处理数据的时候把数据所放在(-1,1)的区间中了,所以用relu函数在<0的时候, 基本和神经元死亡没啥区别了,那么前向死亡,反向传播就更别想了,早点睡吧,赶紧换,sigmoid都比relu强… 然后去掉dropout函数 减少训练的时间

话不多说先上代码

import time

import torch
import torchvision
import torchvision.transforms as transforms
# import matplotlib.pyplot as plt
import numpy as np
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F

import vgg


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # self.f = stack_big((2, 2, 3, 3, 3), ((3, 64), (64, 128), (128, 256), (256, 512)))
        net = []
        for n, c in zip((2, 2, 5, 3), ((3, 64), (64, 128), (128, 256), (256, 512))):
            in_c = c[0]
            out_c = c[1]
            net += [stack_mini(n, in_c, out_c)]
        # self.f = nn.Sequential(*net)
        self.f = nn.Sequential(*net)
        # print(self.f)
        self.fc = nn.Sequential(
            nn.Linear(2 * 2 * 512, 384),
            nn.SELU(True),
            # nn.Tanh(),
            nn.Linear(384, 192),
            nn.SELU(True),
            # nn.Tanh(),
            nn.Linear(192, 10)

        )

    def forward(self, x):
        # x = self.f(x)
        x = self.f[0](x)
        x = self.f[1](x)
        x = self.f[2](x)
        x = self.f[3](x)
        x = x.view(x.shape[0], -1)
        x = self.fc(x)
        return x


def stack_mini(num_convs, in_channels, out_channels):
    '''
    block块 开始以卷积层开始,结束以池化层结束 过程中提取高纬数据
    :param num_convs: 循环次数
    :param in_channels: 输入通道数
    :param out_channels: 输出通道数
    :return:
    '''
    # 定义第一层并转换为list
    net = [nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), nn.ReLU(True)]  # 卷积+激活层
    # 循环定义其它层
    for i in range(num_convs - 1):  # 卷积层+激活层
        # net.append(nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1))
        # net.append(nn.ReLU(True))
        net += [nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), nn.ReLU(True)]
    # 定义池化层
    # net.append(nn.MaxPool2d(2, 2))  # 2*2 步长为2
    net += [nn.MaxPool2d(2, 2)]
    # return net
    return nn.Sequential(*net)


def stack_big(num_convs, channels):
    '''
    创建数据提取模块
    :param num_convs:[循环次数]list
    :param channels:[(输入,输出),(输入维度,输出维度)]list
    :return:数据特征提取网络
    '''
    net = []
    for n, c in zip(num_convs, channels):
        in_c = c[0]
        out_c = c[1]
        net += [stack_mini(n, in_c, out_c)]
    return net


def loadData():
    tf = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
    trainset = torchvision.datasets.CIFAR10(root=
PyTorch中,VGG16是一个经典的深度学习模型,通常用于图像分类任务。要直接实现VGG16而不使用`nn.Sequential`,你需要手动构建每一层并添加到模型中。以下是步骤: 1. 首先,导入所需的库和模块: ```python import torch import torch.nn as nn import torchvision.models.vgg as vgg ``` 2. 获取VGG16的基本结构,通常是去掉最后一层全连接层的部分,因为我们要自定义这部分: ```python features = vgg.VGG(make_layers(vgg.cfgs['D'])).features ``` 这里`make_layers`函数是VGG模型里定义的一个内部函数,它根据配置生成网络的各个卷积层。 3. 创建一个新的自定义模块来组合这些特征层,并保存权重: ```python class VGGBase(nn.Module): def __init__(self, features): super(VGGBase, self).__init__() self.features = features def forward(self, x): for layer in self.features: x = layer(x) return x # 将预训练好的VGG16特征加载到新模块上 vgg_base = VGGBase(features) vgg_base.load_state_dict(torch.load('pretrained_vgg16.pth', map_location='cpu')["model"]) ``` 4. 如果你想保留前向传播过程,你可以像下面这样创建一个简单的模型: ```python class CustomVGG(nn.Module): def __init__(self): super(CustomVGG, self).__init__() # 添加其他必要的层,比如全局平均池化和全连接层,注意需要根据你的任务调整最后的分类层 def forward(self, x): base_output = vgg_base(x) # 使用VGGBase模块获取特征 # 自定义的最后一部分,如FC layers or Pooling custom_layers = ... # 你的自定义操作 output = custom_layers(base_output) return output custom_vgg = CustomVGG() ``` 现在你有了一个名为`custom_vgg`的模型,它可以接收输入数据并输出特征或最终预测。记得替换`custom_layers`部分以适应你的任务需求。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值