深度学习基础第三章-VGG网络

深度学习基础第三章-VGG网络

本模型存放于目录:

E:\python文件\deep-learning-for-image-processing-master\pytorch_classification\Test3_vggnet

一.模型介绍

特点:

  • 通过堆叠多个3x3的卷积核来替代大尺度卷积核(减少所需参数)
  • 论文中提到,可以通过堆叠两个3x3的卷积核替代5x5的卷积核,堆叠三个3x3的卷积核替代7x7的卷积核 (拥有相同的感受野)

pAVk8Ag.jpg

二.数据集-花分类数据集

1.定义预处理函数

1
2
3
4
5
6
7
8
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))])}

2.从磁盘中读取数据集

1
2
3
4
5
6
data_root = os.path.abspath(os.path.join(os.getcwd(), "../.."))  # get data root path
image_path = os.path.join(data_root, "data_set", "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)

3.保存各类比的字典索引

1
2
3
4
5
6
7
# {'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)

4.加载训练集与测试集

1
2
3
4
5
6
7
8
9
10
11
12
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=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))

三.网络模型搭建

1.根据版本提供相应的网络结构

  • 由于vgg网络有很多版本,因此通过字典保存相应不同的结构
1
2
3
4
5
6
7
#字典文件保存各网络模型的配置文件 (特征提取部分)
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'],
}
1
2
3
4
5
6
7
8
9
10
11
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) #最终返回网络模型

2.定义网络模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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),
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) #展平
# 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.xavier_uniform_(m.weight) #使用xavier方法对卷积层参数初始化
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.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)

3.实例化网络模型(使用vgg16)

1
2
3
4
5
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

四·训练模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
model_name = "vgg16" #使用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() #将网络设置为训练模式,此时dropout层将发挥作用
running_loss = 0.0
train_bar = tqdm(train_loader, file=sys.stdout) #利用了 tqdm 库来在训练过程中添加一个进度条,使得用户可以直观地看到数据加载和训练的进度
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(即之前通过 tqdm 包装的 train_loader 迭代器)的描述(description)字段。这个描述字段通常用于在进度条旁边显示额外的信息,比如当前的训练轮次(epoch)、总轮次、以及某个指标(如损失值)的当前值。
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, file=sys.stdout)
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')

五.测试模型效果

  • 代码与AlnexNet部分一致
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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 = "../tulip.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)

with open(json_path, "r") as f:
class_indict = json.load(f)

# 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)
for i in range(len(predict)):
print("class: {:10} prob: {:.3}".format(class_indict[str(i)],
predict[i].numpy()))
plt.show()
-------------本文结束-------------