当前位置: 首页 > news >正文

【深度学习】使用tensorflow实现VGG19网络

【深度学习】使用tensorflow实现VGG19网络

 

 

 

本文章向大家介绍【深度学习】使用tensorflow实现VGG19网络,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

 

 

 

 

VGG网络与AlexNet类似,也是一种CNN,VGG在2014年的 ILSVRC localization and classification 两个问题上分别取得了第一名和第二名。VGG网络非常深,通常有16-19层,卷积核大小为 3 x 3,16和19层的区别主要在于后面三个卷积部分卷积层的数量。第二个用tensorflow独立完成的小玩意儿......

 

 

模型结构

可以看到VGG的前几层为卷积和maxpool的交替,每个卷积包含多个卷积层,后面紧跟三个全连接层。激活函数采用Relu,训练采用了dropout,但并没有像AlexNet一样采用LRN(论文给出的理由是加LRN实验效果不好)。

模型定义

def maxPoolLayer(x, kHeight, kWidth, strideX, strideY, name, padding = "SAME"):"""max-pooling"""return tf.nn.max_pool(x, ksize = [1, kHeight, kWidth, 1],strides = [1, strideX, strideY, 1], padding = padding, name = name)def dropout(x, keepPro, name = None):"""dropout"""return tf.nn.dropout(x, keepPro, name)def fcLayer(x, inputD, outputD, reluFlag, name):"""fully-connect"""with tf.variable_scope(name) as scope:w = tf.get_variable("w", shape = [inputD, outputD], dtype = "float")b = tf.get_variable("b", [outputD], dtype = "float")out = tf.nn.xw_plus_b(x, w, b, name = scope.name)if reluFlag:return tf.nn.relu(out)else:return outdef convLayer(x, kHeight, kWidth, strideX, strideY,featureNum, name, padding = "SAME"):"""convlutional"""channel = int(x.get_shape()[-1]) #获取channel数with tf.variable_scope(name) as scope:w = tf.get_variable("w", shape = [kHeight, kWidth, channel, featureNum])b = tf.get_variable("b", shape = [featureNum])featureMap = tf.nn.conv2d(x, w, strides = [1, strideY, strideX, 1], padding = padding)out = tf.nn.bias_add(featureMap, b)return tf.nn.relu(tf.reshape(out, featureMap.get_shape().as_list()), name = scope.name)

定义了卷积、pooling、dropout、全连接五个模块,使用了上一篇AlexNet中的代码,其中卷积模块去除了group参数,因为网络没有像AlexNet一样分成两部分。接下来定义VGG19。

class VGG19(object):"""VGG model"""def __init__(self, x, keepPro, classNum, skip, modelPath = "vgg19.npy"):self.X = xself.KEEPPRO = keepProself.CLASSNUM = classNumself.SKIP = skipself.MODELPATH = modelPath#build CNNself.buildCNN()def buildCNN(self):"""build model"""conv1_1 = convLayer(self.X, 3, 3, 1, 1, 64, "conv1_1" )conv1_2 = convLayer(conv1_1, 3, 3, 1, 1, 64, "conv1_2")pool1 = maxPoolLayer(conv1_2, 2, 2, 2, 2, "pool1")conv2_1 = convLayer(pool1, 3, 3, 1, 1, 128, "conv2_1")conv2_2 = convLayer(conv2_1, 3, 3, 1, 1, 128, "conv2_2")pool2 = maxPoolLayer(conv2_2, 2, 2, 2, 2, "pool2")conv3_1 = convLayer(pool2, 3, 3, 1, 1, 256, "conv3_1")conv3_2 = convLayer(conv3_1, 3, 3, 1, 1, 256, "conv3_2")conv3_3 = convLayer(conv3_2, 3, 3, 1, 1, 256, "conv3_3")conv3_4 = convLayer(conv3_3, 3, 3, 1, 1, 256, "conv3_4")pool3 = maxPoolLayer(conv3_4, 2, 2, 2, 2, "pool3")conv4_1 = convLayer(pool3, 3, 3, 1, 1, 512, "conv4_1")conv4_2 = convLayer(conv4_1, 3, 3, 1, 1, 512, "conv4_2")conv4_3 = convLayer(conv4_2, 3, 3, 1, 1, 512, "conv4_3")conv4_4 = convLayer(conv4_3, 3, 3, 1, 1, 512, "conv4_4")pool4 = maxPoolLayer(conv4_4, 2, 2, 2, 2, "pool4")conv5_1 = convLayer(pool4, 3, 3, 1, 1, 512, "conv5_1")conv5_2 = convLayer(conv5_1, 3, 3, 1, 1, 512, "conv5_2")conv5_3 = convLayer(conv5_2, 3, 3, 1, 1, 512, "conv5_3")conv5_4 = convLayer(conv5_3, 3, 3, 1, 1, 512, "conv5_4")pool5 = maxPoolLayer(conv5_4, 2, 2, 2, 2, "pool5")fcIn = tf.reshape(pool5, [-1, 7*7*512])fc6 = fcLayer(fcIn, 7*7*512, 4096, True, "fc6")dropout1 = dropout(fc6, self.KEEPPRO)fc7 = fcLayer(dropout1, 4096, 4096, True, "fc7")dropout2 = dropout(fc7, self.KEEPPRO)self.fc8 = fcLayer(dropout2, 4096, self.CLASSNUM, True, "fc8")def loadModel(self, sess):"""load model"""wDict = np.load(self.MODELPATH, encoding = "bytes").item()#for layers in modelfor name in wDict:if name not in self.SKIP:with tf.variable_scope(name, reuse = True):for p in wDict[name]:if len(p.shape) == 1:#bias 只有一维sess.run(tf.get_variable('b', trainable = False).assign(p))else:#weightssess.run(tf.get_variable('w', trainable = False).assign(p)) 

buildCNN函数完全按照VGG的结构搭建网络。

loadModel函数从模型文件中读取参数,采用的模型文件见github上的readme说明。 至此,我们定义了完整的模型,下面开始测试模型。

模型测试

ImageNet训练的VGG有很多类,几乎包含所有常见的物体,因此我们随便从网上找几张图片测试。比如我直接用了之前做项目的图片,为了避免审美疲劳,我们不只用渣土车,还要用挖掘机、采沙船:

然后编写测试代码:

parser = argparse.ArgumentParser(description='Classify some images.')
parser.add_argument('mode', choices=['folder', 'url'], default='folder')
parser.add_argument('path', help='Specify a path [e.g. testModel]')
args = parser.parse_args(sys.argv[1:])if args.mode == 'folder': #测试方式为本地文件夹#get testImagewithPath = lambda f: '{}/{}'.format(args.path,f)testImg = dict((f,cv2.imread(withPath(f))) for f in os.listdir(args.path) if os.path.isfile(withPath(f)))
elif args.mode == 'url': #测试方式为URLdef url2img(url): #获取URL图像'''url to image'''resp = urllib.request.urlopen(url)image = np.asarray(bytearray(resp.read()), dtype="uint8")image = cv2.imdecode(image, cv2.IMREAD_COLOR)return imagetestImg = {args.path:url2img(args.path)}if testImg.values():#some paramsdropoutPro = 1classNum = 1000skip = []imgMean = np.array([104, 117, 124], np.float)x = tf.placeholder("float", [1, 224, 224, 3])model = vgg19.VGG19(x, dropoutPro, classNum, skip)score = model.fc8softmax = tf.nn.softmax(score)with tf.Session() as sess:sess.run(tf.global_variables_initializer())model.loadModel(sess) #加载模型for key,img in testImg.items():#img preprocessresized = cv2.resize(img.astype(np.float), (224, 224)) - imgMean #去均值maxx = np.argmax(sess.run(softmax, feed_dict = {x: resized.reshape((1, 224, 224, 3))})) #网络输入为224*224res = caffe_classes.class_names[maxx]font = cv2.FONT_HERSHEY_SIMPLEXcv2.putText(img, res, (int(img.shape[0]/3), int(img.shape[1]/3)), font, 1, (0, 255, 0), 2) #在图像上绘制结果print("{}: {}n----".format(key,res)) #输出测试结果cv2.imshow("demo", img)cv2.waitKey(0)

如果你看完了我AlexNet的博客,那么一定会发现我这里的测试代码做了一些小的修改,增加了URL测试的功能,可以测试网上的图像 ,测试结果如下:

 

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • mysql mgr集群多主部署
  • 深度学习与机器学习的关系
  • list链表
  • 【AI学习】LangChain学习
  • ArcGIS学习(八)基于GIS平台的控规编制办法
  • 【Node.js】path 模块进行路径处理
  • UE5中的DataTable说明
  • 剪辑视频调色软件有哪些 剪辑视频软件哪个最好 剪辑视频怎么学 剪辑视频的方法和步骤 会声会影2024 会声会影视频制作教程
  • 【研究生复试】计算机软件工程人工智能研究生复试——资料整理(速记版)——JAVA
  • Sora了解资料
  • OpenHarmony下GN语法普法
  • easyx 枪声模拟器
  • h5网页和 Android APP联调,webview嵌入网页,网页中window.open打开新页面,网页只在webview中打开,没有重开一个app窗口
  • html的列表标签
  • 入门【网络安全/黑客】启蒙教程
  • 【前端学习】-粗谈选择器
  • Android Studio:GIT提交项目到远程仓库
  • Docker容器管理
  • egg(89)--egg之redis的发布和订阅
  • GitUp, 你不可错过的秀外慧中的git工具
  • java 多线程基础, 我觉得还是有必要看看的
  • Js基础知识(一) - 变量
  • Vultr 教程目录
  • 对象管理器(defineProperty)学习笔记
  • 关于使用markdown的方法(引自CSDN教程)
  • 机器学习 vs. 深度学习
  • 前端路由实现-history
  • 少走弯路,给Java 1~5 年程序员的建议
  • 使用前端开发工具包WijmoJS - 创建自定义DropDownTree控件(包含源代码)
  • 试着探索高并发下的系统架构面貌
  • 首页查询功能的一次实现过程
  • 微信小程序:实现悬浮返回和分享按钮
  • 原生js练习题---第五课
  • 智能合约开发环境搭建及Hello World合约
  • “十年磨一剑”--有赞的HBase平台实践和应用之路 ...
  • UI设计初学者应该如何入门?
  • # windows 安装 mysql 显示 no packages found 解决方法
  • #162 (Div. 2)
  • #nginx配置案例
  • #我与Java虚拟机的故事#连载14:挑战高薪面试必看
  • (ibm)Java 语言的 XPath API
  • (附源码)计算机毕业设计ssm高校《大学语文》课程作业在线管理系统
  • (转)ObjectiveC 深浅拷贝学习
  • ****** 二十三 ******、软设笔记【数据库】-数据操作-常用关系操作、关系运算
  • .NET C# 配置 Options
  • .net mvc部分视图
  • .NET 实现 NTFS 文件系统的硬链接 mklink /J(Junction)
  • .NET 中创建支持集合初始化器的类型
  • .NET中winform传递参数至Url并获得返回值或文件
  • .ui文件相关
  • @Bean, @Component, @Configuration简析
  • @RestController注解的使用
  • @Transient注解
  • [ C++ ] template 模板进阶 (特化,分离编译)
  • [ CTF ] WriteUp- 2022年第三届“网鼎杯”网络安全大赛(白虎组)