如何使用TensorFlow Hub和代码示例
内容已失效,使用教程可见TensorflowHub官网
任何深度学习框架,为了获得成功,必须提供一系列最先进的模型,以及在流行和广泛接受的数据集上训练的权重,即与训练模型。
TensorFlow现在已经提出了一个更好的框架,称为TensorFlow Hub,它非常易于使用且组织良好。使用TensorFlow Hub,您可以通过几行代码导入大型和流行的模型,自信地执行广泛使用的传输学习活动。TensorFlow Hub非常灵活,可以托管您的模型以供其他用户使用。TensorFlow Hub中的这些模型称为模块。在本文中,让我们看看如何使用TensorFlow Hub模块的基础知识,它是各种类型和代码示例。
前置知识
接下来,让我们看一些可用于了解TensorFlow Hub模块更多细节的重要方面和功能。
1)模块实例化:由TensorFlow Hub网站托管用于不同目的(图像分类,文本嵌入等)的不同模型(Inception,ResNet,ElMo等)组成的各种模块。用户必须浏览模块目录,然后在完成其目的和模型后,需要复制托管模型的URL。然后,用户可以像这样实例化他的模块:
import tensorflow_hub as hub module = hub.Module(<<Module URL as string>>, trainable=True)
除了URL参数,另一个最值得注意的参数是'trainable'。如果用户希望微调/修改模型的权重,则必须将此参数设置为True 。
2)签名:模块的签名指定了每个模块的作用。如果未明确提及签名,则所有模块都带有“默认”签名并使用它。对于大多数模块,当使用“默认”签名时,模型的内部层将从用户中抽象出来。用于列出模块的所有签名名称的函数是get_signature_names()。
import tensorflow_hub as hub
module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
print(module.get_signature_names())
# ['default', 'image_classification', 'image_feature_vector']
import tensorflow_hub as hub
module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
print(module.get_input_info_dict()) # When no signature is given, considers it as 'default'
# {'images': <hub.ParsedTensorInfo shape=(?, 299, 299, 3) dtype=float32 is_sparse=False>}
print(module.get_input_info_dict(signature='image_feature_vector'))
# {'images': <hub.ParsedTensorInfo shape=(?, 299, 299, 3) dtype=float32 is_sparse=False>}
4)预期输出:为了在构建TensorFlow Hub模型之后构建图的剩余部分,有必要知道预期的输出类型。get_output_info_dict()函数用于此目的。请注意,对于“默认”签名,通常只有一个输出,但是当您使用非默认签名时,图表的多个图层将向您公开。
import tensorflow_hub as hub
module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
print(module.get_output_info_dict()) # When no signature is given, considers it as 'default'
# {'default': <hub.ParsedTensorInfo shape=(?, 1001) dtype=float32 is_sparse=False>}
print(module.get_output_info_dict(signature='image_classification'))
# {'InceptionV3/global_pool': <hub.ParsedTensorInfo shape=(?, 1, 1, 2048) dtype=float32 is_sparse=False>,
# 'InceptionV3/Logits': <hub.ParsedTensorInfo shape=(?, 1001) dtype=float32 is_sparse=False>,
# 'InceptionV3/Conv2d_2b_3x3': <hub.ParsedTensorInfo shape=(?, 147, 147, 64) dtype=float32 is_sparse=False>
# ..... Several other exposed layers...... }
5)收集所需的模块层:实例化模块后,必须从模块中提取所需的层/输出并将其添加到图形中。以下是一些方法:
import tensorflow as tf
import tensorflow_hub as hub images = tf.placeholder(tf.float32, (None, 299, 299, 3)) module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
logits1 = module(dict(images=images)) # implies default signature
print(logits1)
# Tensor("module_apply_default/InceptionV3/Logits/SpatialSqueeze:0", shape=(?, 1001), dtype=float32) module_features = module(dict(images=images), signature='image_classification', as_dict=True)
# module_features stores all layers in key-value pairs
logits2 = module_features['InceptionV3/Logits']
print(logits2)
# Tensor("module_apply_image_classification/InceptionV3/Logits/SpatialSqueeze:0", shape=(?, 1001), dtype=float32) global_pool = module_features['InceptionV3/global_pool']
print(global_pool)
# Tensor("module_apply_image_classification/InceptionV3/Logits/GlobalPool:0", shape=(?, 1, 1, 2048), dtype=float32)
import tensorflow as tf with tf.Session() as sess:
sess.run([tf.tables_initializer(), <<other initializers>>])
代码骨架
一旦构建了包含模块,学习算法优化器,目标函数,自定义层等的完整图形,这就是代码的图形部分的框架。
import tensorflow as tf
import tensorflow_hub as hub << Create Placeholders >>
<< Create Dataset and Iterators >> module1 = hub.Module(<< Module URL >>)
logits1 = module1(<< input_dict >>) module2 = hub.Module(<< Module URL >>)
module2_features = module2(<< input_dict >>, signature='default', as_dict=True)
logits2 = module2_features['default'] << Remaining graph, learning algorithms, objective function, etc >> with tf.Session() as sess:
sess.run([tf.tables_initializer(), << other initializers >>]) << Remaining training pipeline >>
我正在使用两个模块。第一个模块使用最小的代码构建,隐式使用默认签名和层。在第二个模块中,我明确指定了默认签名和图层。以类似的方式,我们可以指定非默认签名和图层。
1)图像分类模块
顾名思义,这些模块集用于图像分类。在这类模块中,给出了完整的网络架构。这包括用于分类的最终密集连接层。在这个类别的代码示例中,我将使用Inception V3模块将Kaggle的猫狗分类问题分类为1001个ImageNet类。
import tensorflow as tf
import tensorflow_hub as hub from Dataset import Dataset tf.reset_default_graph()
dataset = Dataset() module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
logits = module(dict(images=dataset.img_data)) softmax = tf.nn.softmax(logits)
top_predictions = tf.nn.top_k(softmax, top_k, name='top_predictions')
2)特征向量模块
这与图像分类模块非常相似,唯一的区别是模块不包括最终的密集分类层。在这个类别的代码示例中,我将针对Hackerearth的多标签动物属性分类问题微调Resnet-50模块。 在微调操作期间,除了定制附加的密集层之外,通常还需要优化模块的最终层。在这种情况下,您必须找到要微调的范围或变量的名称。我附加了代码的相关部分以在特征向量模块中执行此类过程。
module = hub.Module('https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/1',
trainable=True) # Trainable is True since we are going to fine-tune the model
module_features = module(dict(images=dataset.image_data), signature="image_feature_vector",
as_dict=True)
features = module_features["default"]
with tf.variable_scope('CustomLayer'):
weight = tf.get_variable('weights', initializer=tf.truncated_normal((2048, n_class)))
bias = tf.get_variable('bias', initializer=tf.ones((n_class)))
logits = tf.nn.xw_plus_b(features, weight, bias)
# Find out the names of all variables present in graph
print(tf.all_variables())
# After finding the names of variables or scope, gather the variables you wish to fine-tune
var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='CustomLayer')
var_list2 = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='module/resnet_v2_50/block4')
var_list.extend(var_list2)
# Pass this set of variables into your optimiser
optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss, var_list=var_list)
如果模块图中的节点没有直观命名(非常不可能的情况),则必须弄清楚模块的体系结构,然后将它们映射到正在打印的节点。
在代码示例中,我已经调整了最后几层变量属于'resnet_v2_50 / block4'的变量范围。通过10个时期的训练,你可以毫不费力地获得这个问题的F1分数0.95819。
3)视频分类模块
视频分类是指对视频片段中发生的活动的性质进行分类。在代码示例中,我已经在Inception 3D模块上训练了包含27个类的20BN-Jester数据集。再说一次,只有3个训练时期,我的准确率达到了91.45%。模块代码的相关部分如下所示。
import tensorflow as tf
import tensorflow_hub as hub from Dataset import Dataset
dataset = Dataset() module = hub.Module("https://tfhub.dev/deepmind/i3d-kinetics-400/1", trainable=True)
features = module(dict(rgb_input=dataset.image_data)) n_class = 27
with tf.variable_scope('CustomLayer'):
weight = tf.get_variable('weights',
initializer=tf.truncated_normal((400, n_class)))
bias = tf.get_variable('bias', initializer=tf.ones((n_class)))
logits = tf.nn.xw_plus_b(features, weight, bias)
为了测试模型的准确性,我构建了一个简单的实时视频分类应用程序,这里是一个小视频
4)文本嵌入模型
module = hub.Module('https://tfhub.dev/google/elmo/2', trainable=True)
embeddings = module(dict(text=dataset.text_data))
embeddings = tf.expand_dims(embeddings, axis=1)
with tf.variable_scope('Layer1'):
cell_fw1 = tf.nn.rnn_cell.LSTMCell(num_units=128, state_is_tuple=True)
cell_bw1 = tf.nn.rnn_cell.LSTMCell(num_units=128, state_is_tuple=True)
outputs1, states1 = tf.nn.bidirectional_dynamic_rnn(
cell_fw=cell_fw1,
cell_bw=cell_bw1,
inputs=embeddings)
rnn_output = tf.reshape(outputs1[0], (-1, 128))
with tf.variable_scope('Layer2'):
weight2 = tf.get_variable('weight', initializer=tf.truncated_normal((128, n_class)))
bias2 = tf.get_variable('bias', initializer=tf.ones(n_class))
logits = tf.nn.xw_plus_b(rnn_output, weight2, bias2)
5)图像增强模块
图像增强是流水话训练中的一个重要组成部分,可以提高模型的准确性。所有图像增强模块(在编写本文时)都没有任何变量,因此,这些模块不具有可调性/可训练性。使用'from_decoded_images'的签名,您可以直接将图像提供给这些模块。下面示出了示例代码块以及生成的增强图像。
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow.contrib.image # Needed for Image Augmentation modules from Dataset import Dataset
dataset = Dataset() module = hub.Module('https://tfhub.dev/google/image_augmentation/nas_svhn/1')
input_dict = dict(image_size=image_size, # Output Image size
images=dataset.img_data, # Has the image in Numpy data format
augmentation=True)
aug_images = module(input_dict, signature='from_decoded_images')

6)对象检测模块
对象检测模块不支持微调,因此如果您有自己的数据集,则必须从头开始执行培训。目前也不支持批量处理数据。在代码示例中,我将仅使用Inception-ResNet V2模块上的FasterRCNN对图像进行推断。我附上了下面模块生成的代码和图像的模块部分。
import tensorflow as tf
import tensorflow_hub as hub from Dataset import Dataset
dataset = Dataset() module = hub.Module('https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1')
detector = module(dict(images=dataset.image_data), as_dict=True) class_entities = detector['detection_class_entities']
boxes = detector['detection_boxes']
scores = detector['detection_scores']
class_labels = detector['detection_class_labels']
class_names = detector['detection_class_names']
7)生成器模型
这些对应于生成性对抗网络(GAN)。一些模块没有暴露其网络的Discriminator部分。就像对象检测一样,即使在代码示例中,我也只是在进行推理。使用在CelebA数据集上训练的Progressive GAN模块,我将生成新面孔。我附上了下面模块生成的代码和图像的模块部分 。
import tensorflow as tf
import tensorflow_hub as hub from Dataset import Dataset
dataset = Dataset() module = hub.Module("https://tfhub.dev/google/progan-128/1")
images = module(dataset.latent_vector_space)
对应的模型在TensorFlow Hub官网也有示例,可以在Colab上复现。例如,目标检测Colab。
原文链接:https://medium.com/ymedialabs-innovation/how-to-use-tensorflow-hub-with-code-examples-9100edec29af
如何使用TensorFlow Hub和代码示例的更多相关文章
- 高级渲染技巧和代码示例 GPU Pro 7
下载代码示例 移动设备正呈现着像素越来越高,屏幕尺寸越来越小的发展趋势. 由于像素着色的能耗非常大,因此 DPI 的增加以及移动设备固有的功耗受限环境为降低像素着色成本带来了巨大的压力. MSAA 有 ...
- Java8-Function使用及Groovy闭包的代码示例
导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...
- [IOS 开发] 懒加载 (延迟加载) 的基本方式,好处,代码示例
懒加载的好处: 1> 不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强 2> 每个属性的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合 ...
- SELECT控件操作的JS代码示例
SELECT控件操作的JS代码示例 1 检测是否有选中 if(objSelect.selectedIndex > -1) { //说明选中 } else { //说明没有选中 } 2.动态创建s ...
- 转:HIBERNATE一些_方法_@注解_代码示例---写的非常好
HIBERNATE一些_方法_@注解_代码示例操作数据库7步骤 : 1 创建一个SessionFactory对象 2 创建Session对象 3 开启事务Transaction : hibernate ...
- Python实现各种排序算法的代码示例总结
Python实现各种排序算法的代码示例总结 作者:Donald Knuth 字体:[增加 减小] 类型:转载 时间:2015-12-11我要评论 这篇文章主要介绍了Python实现各种排序算法的代码示 ...
- C#与数据库访问技术总结(十五)之 DataAdapter对象代码示例
DataAdapter对象代码示例 下面的代码将说明如何利用DataAdapter对象填充DataSet对象. private static string strConnect=" data ...
- C#与数据库访问技术总结(六)之Command对象创建SQl语句代码示例
Command对象创建SQl语句代码示例 说明:前面介绍了 Command 对象的方法和一些属性,回顾一下 Command对象主要用来执行SQL语句.利用Command对象,可以查询数据和修改数据. ...
- 领域驱动开发推荐代码示例 — Microsoft NLayerApp
简介: Microsoft NLayerApp是由微软西班牙团队出品的基于.NET 4.0的“面向领域N层分布式架构”代码示例,在codeplex上的地址是:http://microsoftnlaye ...
随机推荐
- POJ - 2955 Brackets括号匹配(区间dp)
Brackets We give the following inductive definition of a “regular brackets” sequence: the empty sequ ...
- yzm10的ACM集训小感
7月30号,ACM集训进行了两周,一切都已on the right way.这时的我适时地从题海中探出头,其实除了刷题,也该写点什么来总结下过去.首先,在第一周里,我学习了数据结构,知道了STL这么一 ...
- 数据库路由中间件MyCat - 使用篇(3)上篇
此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 全局序列号 数据切分后,原有的关系数据库中的主键约束在分布式条件下将无法使用,因此需要引入外部机制保证数据唯 ...
- jquery获取元素对应高度
https://www.cnblogs.com/sntetwt/p/3823592.html 获取点击元素距离页面的高度 $(select).offset().top - $(document).sc ...
- OpenStack日志分析
日志文件说明 Nova日志 OpenStack计算服务日志位于/var/log/nova目录下(此目录在Controller和Compute节点都存在),默认权限拥有者是nova用户 文件名 作用 n ...
- Solr6.7 学习笔记(01) -- 目录结构
Solr解压后的目录结构 --contrib: Solr的一些扩展 --analysis-extras: 包含一些文本分析组件及其依赖 --clustering: 包含一个用于集群搜索结果的引擎 -- ...
- 51nod1412(dp)
题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1412 代码: #include <bits/stdc+ ...
- IT兄弟连 JavaWeb教程 JSON和JSON字符串
JSON (JavaScript Object Notation)是JavaScript语言中的一种对象类型.JSON的好处是易于阅读和解析.当客户端和服务器端需要交互大量数据时,使用JSON格式传输 ...
- Etherscan API 中文文档-智能合约
本文原文链接 点击这里获取Etherscan API 中文文档(完整版) 完整内容排版更好,推荐读者前往阅读. 智能合约(Contracts) 智能合约相关的 API,接口的参数说明请参考Ethers ...
- Jenkins+Git+Docker+K8s部署
准备工作 Jenkins已安装 Docker和K8s部署运行成功 代码管理工具使用Git 最近公司项目使用Jenkins+Git+Docker+K8s进行持续化构建部署,这里笔者整理了一下构建部署的相 ...