如何使用 tf.layers 类而不是函数 [英] How to use tf.layers classes instead of functions
问题描述
tf.Layer 模块似乎有两种风格:函数和类.我通常直接使用函数(例如,tf.layers.dense),但我想知道如何直接使用类(tf.layers.Dense).我已经开始在 tensorflow 中尝试新的 Eager Execution 模式,我认为在那里使用类也会很有用,但我还没有在文档中看到好的例子.TF 文档中是否有任何部分显示了这些是如何使用的?
It seems that tf.Layer modules come in two flavours: functions and classes. I normally use the functions directly (e.g, tf.layers.dense) but I'd like to know how to use classes directly (tf.layers.Dense). I've started experimenting with the new eager execution mode in tensorflow and I think using classes are going to be useful there as well but I haven't seen good examples in the documentation. Is there any part of TF documentation that shows how these are used?
我想在这些层在 __init__
中实例化的类中使用它们是有意义的,然后当输入时它们在 __call__
方法中链接和尺寸已知吗?
I guess it would make sense to use them in a class where these layers are instantiated in the __init__
and then they're linked in the __call__
method when the inputs and dimensions are known?
这些 tf.layer 类是否与 tf.keras.Model
相关?是否有使用 tf.layers
的等效包装类?
Are these tf.layer classes related to tf.keras.Model
? Is there an equivalent wrapper class for using tf.layers
?
更新:对于急切执行,必须继承 tfe.Network
.有一个例子这里
Update: for eager execution there's tfe.Network
that must be inherited. There's an example here
推荐答案
tf.layers
和 tf.keras.layer
类通常是可以互换的,实际上在头部(因此到下一个版本 - 1.9),前者实际上 从后者继承.
tf.layers
and tf.keras.layer
classes are generally interchangeable and in fact at head (and thus by the next release - 1.9), the former actually inherits from the latter.
TensorFlow 正在整合 tf.keras
API 以构建模型,因为这使得状态所有权更加明确(例如,参数由 Layer
对象拥有",与将所有模型参数放在与完整图形关联的集合"中的功能风格相反).这种风格适用于 Eager Execution 和图构建(每个版本都在改进对 Eager Execution 的支持).我建议使用 tf.keras.layers
和 tf.keras.Model
.
TensorFlow is moving towards consolidating on tf.keras
APIs for constructing models as that makes state ownership more explicit (e.g., parameters are "owned" by the Layer
object, as opposed to the functional style where all model parameters are put in a "collection" associated with the complete graph). This style works well for both eager execution and graph construction (support for eager execution is improving with every release). I'd recommend using tf.keras.layers
and tf.keras.Model
.
一些您可能会觉得有用的示例:
Some examples that you may find useful:
tensorflow/models中的MNIST代码>
存储库- 程序员指南
- 其他eager 执行示例(完全相同的模型定义适用于图执行和急切执行).
- MNIST in the
tensorflow/models
repository - The programmer's guide
- Other eager execution samples (where the exact same model definition works for both graph execution and eager execution).
并非所有现有的 TensorFlow 示例都已迁移到这种样式,但它们会慢慢迁移.
Not all existing TensorFlow examples have been moved to this style, but they slowly will.
希望有所帮助.
这篇关于如何使用 tf.layers 类而不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!