网络简介
VGG是由Simonyan 和Zisserman在文献《Very Deep Convolutional Networks for Large Scale Image Recognition》中提出卷积神经网络模型,其名称来源于作者所在的牛津大学视觉几何组(Visual Geometry Group)的缩写。
结构分析
我们针对VGG16进行具体分析发现,VGG16共包含:
13个卷积层(Convolutional Layer),分别用conv3-XXX表示
3个全连接层(Fully connected Layer),分别用FC-XXXX表示
5个池化层(Pool layer),分别用maxpool表示
其中,卷积层和全连接层具有权重系数,因此也被称为权重层,总数目为13+3=16,这即是VGG16中16的来源。(池化层不涉及权重,因此不属于权重层,不被计数)。
参数变化
尽管VGG的结构简单,但是所包含的权重数目却很大,达到了惊人的138 357 544 个参数。这些参数包括卷积核权重和全连接层权重。
例如,对于第一层卷积,由于输入图的通道数是3,网络必须学习大小为3×3,通道数为3的的卷积核,这样的卷积核有64个,因此总共有(3×3 × 3)× 64 = 1728个参数。
计算全连接层的权重参数数目的方法为:
前一层节点数×本层的节点数。
因此,全连接层的参数分别为:
7 × 7 × 512 × 4096 = 1027,645,444
4096 × 4096 = 16,781,312
4096 × 1000 = 4,097 000
实践结果
我们应用Keras对VGG16的图像分类能力进行试验。
Keras是一个高层神经网络API,Keras由纯Python编写 ,是tensorflow和Theano等底层深度学习库的高级封装 。使用Keras时,我们不需要直接调用底层API构建深度学习网络,仅调用keras已经封装好的函数即可。
本次试验平台:python 3.6 + tensorflow 1.8 + keras 2.2,Google Colab
源代码如下:
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import matplotlib.pyplot as plt
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
import numpy as np
def percent(value):
return '%.2f%%' % (value * 100)
# include_top=True,表示會載入完整的 VGG16 模型,包括加在最後3層的卷積層
# include_top=False,表示會載入 VGG16 的模型,不包括加在最後3層的卷積層,通常是取得 Features
# 若下載失敗,請先刪除 c:\<使用者>\.keras\models\vgg16_weights_tf_dim_ordering_tf_kernels.h5
model = VGG16(weights='imagenet', include_top=True)
# Input:要辨識的影像
img_path = 'frog.jpg'
#img_path = 'tiger.jpg' 并转化为224*224的标准尺寸
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img) #转化为浮点型
x = np.expand_dims(x, axis=0)#转化为张量size为(1, 224, 224, 3)
x = preprocess_input(x)
# 預測,取得features,維度為 (1,1000)
features = model.predict(x)
# 取得前五個最可能的類別及機率
pred=decode_predictions(features, top=5)[0]
#整理预测结果,value
values = []
bar_label = []
for element in pred:
values.append(element[2])
bar_label.append(element[1])
#绘图并保存
fig=plt.figure(u"Top-5 预测结果")
ax = fig.add_subplot(111)
ax.bar(range(len(values)), values, tick_label=bar_label, width=0.5, fc='g')
ax.set_ylabel(u'probability')
ax.set_title(u'Top-5')
for a,b in zip(range(len(values)), values):
ax.text(a, b+0.0005, percent(b), ha='center', va = 'bottom', fontsize=7)
fig = plt.gcf()
plt.show()
name=img_path[0:-4]+'_pred'
fig.savefig(name, dpi=200)
上述程序的基本流程是:
1.载入相关模块,keras ,matplotlib,numpy
2.下载已经训练好的模型文件:
3.导入测试图像
4.应用模型文件对图像分类
根据小白实测,该模型大小为500M左右
程序运行结束,会在工作目录下生成测试图片的预测图,给出了最有可能的前5个类列。名称为:测试文件名_pred.png