VGGNet网络及代码

  VGGNet 是牛津大学计算机视觉组(Visual Geometry Group)和 GoogleDeepMind 公司的研究员一起研发的的深度卷积神经网络。VGG 模型是 2014 年 ILSVRC 竞赛的第二名(第一名是GoogLeNet),但是 VGG 模型在多个迁移学习任务中的表现要优于 googLeNet。而且,从图像中提取 CNN 特征,VGG 模型是首选算法。它的缺点在于,参数量有 140M 之多,需要更大的存储空间。

  VGG 模型通过反复的堆叠 3*3 的小型卷积核和 2*2 的最大池化层,成功的构建了16~19 层深的卷积神经网络。其突出贡献在于证明使用很小的卷积(3*3),增加网络深度可以有效提升模型的效果,而且 VGGNet 对其他数据集具有很好的泛化能力。

VGG的特点

(1)小卷积核,将卷积核全部替换为 3x3;
(2)小池化核,相比 AlexNet 的 3x3 的池化核,VGG 全部为 2x2 的池化核;
(3)层数更深特征图更宽;
(4)亮点:通过堆叠多个 3x3 的卷积核来替代大尺度卷积核(减少所需参数)。两个 3x3 的卷积堆叠获得的感受野大小相当一个 5x5 的卷积;而 3 个 3x3 卷积的堆叠获取到的感受野相当于一个 7x7 的卷积。

感受野

  在卷积神经网络中,决定某一层输出结果中一个元素所对应的输入层的区域大小,被称作感受野(receptive field)。 通俗的解释是,输出 feature map 上的一个单元对应输入层上的区域大小。

  感受野计算公式:
F ( i ) = ( F ( i + 1 ) − 1 ) ∗ S t r i d e + K s i z e F(i) = (F(i+1) - 1) * Stride + Ksize F(i)=(F(i+1)1)Stride+Ksize  F(i) 第 i 层的感受野
  Stride 第 i 层的步距
  Ksize 卷积核/池化核的尺寸

  例:Feayure map: F = 1
    Conv3*3 (1): F = (1 - 1) * 1 + 3 = 3
    Conv3*3 (2): F = (3 - 1) * 1 + 3 = 5
    Conv3*3 (3): F = (5 - 1) * 1 + 3 = 7
  由此可见 3 个 3x3 卷积的堆叠获取到的感受野相当于一个7x7的卷积。

VGG模型


VGG 模型有以下几个共同点:
(1)每个 VGG 网络都有 5 个池化层,3 个 FC 层,1 个 softmax 层
(2)在 FC 层中间采用 dropout 层,防止过拟合
(3)所有的卷积层 Conv 的 stride = 1,padding = 1
(4)所有的池化层 Maxpool 的 size = 2,stride = 2

VGG16结构图


VGG16
卷积层:13 层 3*3 卷积核
池化层:max-pooling 2*2 池化核
全连接层:3 层
输出层:Softmax

  所有隐层的激活单元都采用** ReLU 函数**,VGGNet 不使用局部响应标准化(LRN),这种标准化并不能在 ILSVRC 数据集上提升性能,却导致更多的内存消耗和计算时间.

代码

这里使用 pytorch 框架构建 VGG16 模型,以花卉为数据集训练
model.py

import torch.nn as nn
import torch


class VGG(nn.Module):
    def __init__(self, features, num_classes=1000, init_weights=False):
        super(VGG, self).__init__()
        self.features = features
        # 分类网络--全连接层
        self.classifier = nn.Sequential(
            nn.Dropout(p=0.5),
            nn.Linear(512*7*7, 4096),
            nn.ReLU(True),
            nn.Dropout(p=0.5),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Linear(4096, num_classes)
        )
        # 初始化权重
        if init_weights:
            self._initialize_weights()

    def forward(self, x):
        x = self.features(x) # N*3*224*224
        x = torch.flatten(x, start_dim=1) # 展平N*512*7*7
        x = self.classifier(x) # N*512*7*7
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.xavier_uniform_(m.weight) # 该方法也被称为glorot的初始化
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0) # 偏值置为0
            elif isinstance(m, nn.Linear):
                nn.init.xavier_uniform_(m.weight) # 初始化
                nn.init.constant_(m.bias, 0) # 偏值置为0


# 特征提取网络--卷积层和池化层
def make_features(cfg: list):
    layers = []
    in_channels = 3
    for v in cfg:  # 遍历列表
        if v == "M":  # 池化层
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:  # 卷积层
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            layers += [conv2d, nn.ReLU(True)]
            in_channels = v  # 下一层的输入通道数,是上一层的输出
    return nn.Sequential(*layers)

# vgg字典
cfgs = {
    'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}

# 自行选择用vgg的哪个模型,这里使用vgg16
def vgg(model_name="vgg16", **kwargs):
    try:
        cfg = cfgs[model_name] # 得到vgg16对应的列表
    except:
        print("Warning: model number {} not in cfgs dict!".format(model_name))
        exit(-1)
    # 搭建模型
    model = VGG(make_features(cfg), **kwargs)
    return model

train.py

import torch.nn as nn
from torchvision import transforms, datasets
import json
import os
import torch.optim as optim
from model import vgg
import torch

# 检测使用 gpu or cpu
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

data_transform = {
    "train": transforms.Compose([transforms.RandomResizedCrop(224),
                                 transforms.RandomHorizontalFlip(),
                                 transforms.ToTensor(),
                                 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]),
    "val": transforms.Compose([transforms.Resize((224, 224)),
                               transforms.ToTensor(),
                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])}

image_path = "data_set/flower_data/"  # 数据集路径
train_dataset = datasets.ImageFolder(root=image_path+"train",
                                     transform=data_transform["train"])
train_num = len(train_dataset)

# {'daisy':0, 'dandelion':1, 'roses':2, 'sunflower':3, 'tulips':4}
flower_list = train_dataset.class_to_idx
cla_dict = dict((val, key) for key, val in flower_list.items())
# 将字典写入json文件中
json_str = json.dumps(cla_dict, indent=4)
with open('class_indices.json', 'w') as json_file:
    json_file.write(json_str)

batch_size = 32
train_loader = torch.utils.data.DataLoader(train_dataset,
                                           batch_size=batch_size, shuffle=True,
                                           num_workers=0)

validate_dataset = datasets.ImageFolder(root=image_path + "val",
                                        transform=data_transform["val"])
val_num = len(validate_dataset)
validate_loader = torch.utils.data.DataLoader(validate_dataset,
                                              batch_size=batch_size, shuffle=False,
                                              num_workers=0)

# vgg16模型,花卉数据集5个类别
model_name = "vgg16"
net = vgg(model_name=model_name, num_classes=5, init_weights=True)
net.to(device)
loss_function = nn.CrossEntropyLoss()  # 损失函数
optimizer = optim.Adam(net.parameters(), lr=0.0001)  # 优化器Adam,定义学习率

# 开始训练
print('Start training...')
best_acc = 0.0  # 最高精度
save_path = './{}Net.pth'.format(model_name)  # 保存
for epoch in range(30):  # epoch训练次数--30次
    # train
    net.train()
    running_loss = 0.0
    for step, data in enumerate(train_loader, start=0):
        images, labels = data
        optimizer.zero_grad()
        outputs = net(images.to(device))
        loss = loss_function(outputs, labels.to(device))
        loss.backward()
        optimizer.step()

        running_loss += loss.item()  # 累加损失值
        # 打印训练过程
        rate = (step + 1) / len(train_loader)
        a = "*" * int(rate * 50)
        b = "." * int((1 - rate) * 50)
        print("\rtrain loss: {:^3.0f}%[{}->{}]{:.3f}".format(int(rate * 100), a, b, loss), end="")
    print()

    # validate
    net.eval()
    acc = 0.0  # accumulate accurate number / epoch
    with torch.no_grad():
        for val_data in validate_loader:
            val_images, val_labels = val_data
            optimizer.zero_grad()
            outputs = net(val_images.to(device))
            predict_y = torch.max(outputs, dim=1)[1]
            acc += (predict_y == val_labels.to(device)).sum().item()
        val_accurate = acc / val_num
        if val_accurate > best_acc:
            best_acc = val_accurate
            torch.save(net.state_dict(), save_path)
        print('[epoch %d] train_loss: %.3f  test_accuracy: %.3f' %
              (epoch + 1, running_loss / step, val_accurate))

print('Finished Training')

predict.py

import torch
from model import vgg
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
import json

data_transform = transforms.Compose(
    [transforms.Resize((224, 224)),
     transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

img = Image.open("data_set/flower_data/predict_flower.jpg") # 载入图像
plt.imshow(img)
img = data_transform(img) # [C, H, W],转换图像为tensor
img = torch.unsqueeze(img, dim=0) # [N, C, H, W],增加一个维度N

# 读取类别
try:
    json_file = open('./class_indices.json', 'r')
    class_indict = json.load(json_file)
except Exception as e:
    print(e)
    exit(-1)

# 建立模型
model = vgg(model_name="vgg16", num_classes=5)
# 载入保存的权重文件
model_weight_path = "vgg16Net.pth"
model.load_state_dict(torch.load(model_weight_path))
model.eval()
with torch.no_grad():
    # 预测类别
    output = torch.squeeze(model(img))
    predict = torch.softmax(output, dim=0)
    predict_cla = torch.argmax(predict).numpy()
print(class_indict[str(predict_cla)], predict[predict_cla].item())

# 画图
name1 = class_indict[str(predict_cla)]
name2 =predict[predict_cla].numpy()
plt.title("This is %s. The accuracy is %s"%(name1, name2),color='red')
plt.show()

训练耗时大概2-3个小时吧

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值