深度学习(四)——VGG+Pytorch实现
作者:互联网
简介
VGG是牛津大学的Visual Geometry Group的组提出的。该网络是在ILSVRC 2014上的相关工作(定位任务第一,分类任务第二),主要工作是证明了增加网络的深度能够在一定程度上影响网络的最终性能(对比了多个不同深度网络的性能)。
从上表可以发现,VGG只使用了两个网络就能获得非常好的效果。
主要方法
采用3x3卷积核
AlexNet采用了 11x11 7x7 5x5较大卷积核,而在VGG中,使用连续的 3x3 卷积核代替大卷积核,可以在保持感受野不变的情况下,减小参数量。
感受野计算
计算公式如下
下面证明了为什么2个 3x3 的卷积核和1个 5x5 的卷积感受野一样
F(2) = 3
F(1) = (3-1)X1 + 3=5
而2个 3x3 的卷积核的参数量为 2X(9XC^2),1个 5x5 的卷积核的参数量为 25XC^2,C为输入和输出的通道数,并且层数会提高网络性能。
网络结构
除了A-LRN采用了LRN(发现并没有什么用),以及C采用了1x1卷积核,其它都只使用了3x3卷积核。
多尺度训练和测试
使用多个尺度训练与测试,可以提高网络的性能。
multi-crop evaluation与 dense evaluation
multi-crop evaluation就是裁剪为多个图片然后塞进网络进行测试,而dense evaluation是将最后的三层全连接层转化为全卷积层,这样可以接受所有尺度的图片。实验发现,这两种方法是互补的,因为他们关注的卷积边界情况不同,multi-crop为0填充,而dense为相邻像素填充。所以两者方法都使用会产生最好的结果。
参数初始化
除了A随机初始化参数,其它更深的网络使用了A网络第一个四个卷积层以及最后三个全连接的参数,随机初始化从零均值10-2方差的正态分布中采样获得,偏差初始化为0。并且发现使用Glorot and Bengio的初始化方法可以获得同样的效果。
Pytorch实现
从http://download.tensorflow.org/example_images/flower_photos.tgz下载数据集
执行下面代码,将数据集划分为训练集与验证集。
split_data.py
import os
from shutil import copy
import random
def mkfile(file):
if not os.path.exists(file):
os.makedirs(file)
file = 'flower_data/flower_photos'
flower_class = [cla for cla in os.listdir(file) if ".txt" not in cla]
mkfile('flower_data/train')
for cla in flower_class:
mkfile('flower_data/train/'+cla)
mkfile('flower_data/val')
for cla in flower_class:
mkfile('flower_data/val/'+cla)
split_rate = 0.1
for cla in flower_class:
cla_path = file + '/' + cla + '/'
images = os.listdir(cla_path)
num = len(images)
eval_index = random.sample(images, k=int(num*split_rate))
for index, image in enumerate(images):
if image in eval_index:
image_path = cla_path + image
new_path = 'flower_data/val/' + cla
copy(image_path, new_path)
else:
image_path = cla_path + image
new_path = 'flower_data/train/' + cla
copy(image_path, new_path)
print("\r[{}] processing [{}/{}]".format(cla, index+1, num), end="") # processing bar
print()
print("processing done!")
model.py
import torch.nn as nn
import torch
# official pretrain weights
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth'
}
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.Linear(512 * 7 * 7, 4096), # 第一层全连接层
nn.ReLU(True),
nn.Dropout(p=0.5), # 50%的比例随机失活
nn.Linear(4096, 4096), # 第二层全连接层
nn.ReLU(True),
nn.Dropout(p=0.5),
nn.Linear(4096, num_classes) # 第三层全连接层
)
if init_weights: # 是否进行权重初始化
self._initialize_weights()
# 正向传播过程
def forward(self, x):
# N x 3 x 224 x 224
x = self.features(x) # 输入到特征提取网络
# N x 512 x 7 x 7
x = torch.flatten(x, start_dim=1) # 展平处理,从第1维度展平(第0维度为batch)
# N x 512*7*7
x = self.classifier(x) # 输入到分类网络中,得到输出
return x
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
# nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
# 构建提取特征网络结构
def make_features(cfg: list): # 传入对应配置的列表
layers = [] # 定义空列表,存放每一层的结构
in_channels = 3 # 输入为RGB图片,输入通道为3
for v in cfg: # 遍历配置列表
if v == "M": # 如果为M,则为池化层,创建一个最大池化下采样层
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else: # 不等于M,则为数字,创建卷积层
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
layers += [conv2d, nn.ReLU(True)] # 每个卷积层都采用RELU激活函数,将定义好的卷积层和RELU拼接
in_channels = v
return nn.Sequential(*layers) # 非关键字参数,*layers可以传递任意数量的实参,以元组的形式导入
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'],
}
# 实例化配置模型
def vgg(model_name="vgg16", **kwargs):
assert model_name in cfgs, "Warning: model number {} not in cfgs dict!".format(model_name)
cfg = cfgs[model_name]
model = VGG(make_features(cfg), **kwargs) # 可以传递任意数量的实参,以字典的形式导入
return model
train.py
VGG网络还是很大的,如果发现训不了,可以调小batch_size,或者使用cpu训练。
import os
import json
import torch
import torch.nn as nn
from torchvision import transforms, datasets
import torch.optim as optim
from tqdm import tqdm
from model import vgg
def main():
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# device = "cpu" #使用cpu训练
print("using {} device.".format(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))])}
data_root = os.getcwd()
image_path = data_root + "/flower_data/" # flower data set path
assert os.path.exists(image_path), "{} path does not exist.".format(image_path)
train_dataset = datasets.ImageFolder(root=os.path.join(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())
# write dict into json file
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
nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers
print('Using {} dataloader workers every process'.format(nw))
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size, shuffle=True,
num_workers=nw)
validate_dataset = datasets.ImageFolder(root=os.path.join(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=nw)
print("using {} images for training, {} images for validation.".format(train_num,
val_num))
# test_data_iter = iter(validate_loader)
# test_image, test_label = test_data_iter.next()
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)
epochs = 30
best_acc = 0.0
save_path = './{}Net.pth'.format(model_name)
train_steps = len(train_loader)
for epoch in range(epochs):
# train
net.train()
running_loss = 0.0
train_bar = tqdm(train_loader)
for step, data in enumerate(train_bar):
images, labels = data
optimizer.zero_grad()
outputs = net(images.to(device))
loss = loss_function(outputs, labels.to(device))
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
train_bar.desc = "train epoch[{}/{}] loss:{:.3f}".format(epoch + 1,
epochs,
loss)
# validate
net.eval()
acc = 0.0 # accumulate accurate number / epoch
with torch.no_grad():
val_bar = tqdm(validate_loader)
for val_data in val_bar:
val_images, val_labels = val_data
outputs = net(val_images.to(device))
predict_y = torch.max(outputs, dim=1)[1]
acc += torch.eq(predict_y, val_labels.to(device)).sum().item()
val_accurate = acc / val_num
print('[epoch %d] train_loss: %.3f val_accuracy: %.3f' %
(epoch + 1, running_loss / train_steps, val_accurate))
if val_accurate > best_acc:
best_acc = val_accurate
torch.save(net.state_dict(), save_path)
print('Finished Training')
if __name__ == '__main__':
main()
predict.py
import os
import json
import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
from model import vgg
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
def main():
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
data_transform = transforms.Compose(
[transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# load image
img_path = "./sunflower.jpg"
assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path)
img = Image.open(img_path)
plt.imshow(img)
# [N, C, H, W]
img = data_transform(img)
# expand batch dimension
img = torch.unsqueeze(img, dim=0)
# read class_indict
json_path = './class_indices.json'
assert os.path.exists(json_path), "file: '{}' dose not exist.".format(json_path)
json_file = open(json_path, "r")
class_indict = json.load(json_file)
# create model
model = vgg(model_name="vgg16", num_classes=5).to(device)
# load model weights
weights_path = "./vgg16Net.pth"
assert os.path.exists(weights_path), "file: '{}' dose not exist.".format(weights_path)
model.load_state_dict(torch.load(weights_path, map_location=device))
model.eval()
with torch.no_grad():
# predict class
output = torch.squeeze(model(img.to(device))).cpu()
predict = torch.softmax(output, dim=0)
predict_cla = torch.argmax(predict).numpy()
print_res = "class: {} prob: {:.3}".format(class_indict[str(predict_cla)],
predict[predict_cla].numpy())
plt.title(print_res)
print(print_res)
plt.show()
if __name__ == '__main__':
main()
Output:
标签:val,nn,VGG,Pytorch,train,深度,path,512,data 来源: https://blog.csdn.net/weixin_44491423/article/details/122390153