gpt4 book ai didi

tensorflow - 即使我们不使用model.fit,我们什么时候应该继承keras.Model而不是keras.layers.Layer?

转载 作者:行者123 更新时间:2023-12-03 13:09:29 27 4
gpt4 key购买 nike

在一些使用 tf2 的 Tensorflow 教程(例如 Neural Machine Translation with AttentionEager essentials )中,他们定义了自定义 tf.keras.Model s 而不是 tf.keras.layers.Layer s(例如 BahdanauAttention(tf.keras.Model):)

另外,Models: composing layers文档使用 tf.keras.Model明确地。该部分说:

The main class used when creating a layer-like thing which contains other layers is tf.keras.Model. Implementing one is done by inheriting from tf.keras.Model.



听起来我们需要继承 tf.keras.Model定义组成子层的层。

但是,据我检查,即使我定义了 ResnetIdentityBlock,这段代码也能工作。作为 tf.keras.layers.Layer的子类.其他两个教程适用于 Layer也。
除此之外, another tutorial

Model is just like a Layer, but with added training and serialization utilities.



因此,我不知道 tf.keras.Model 之间的真正区别是什么和 tf.keras.layers.Layer以及为什么这三个带有 Eager 执行的教程使用 tf.keras.Model尽管他们不使用 tf.keras.Model 的训练和序列化实用程序.

为什么需要继承 tf.keras.Model在那些教程中?

附加评论
Model 的实用程序仅适用于 Layer 的特殊子集( Layers whose call receive only one input )。因此,我认为“总是扩展模型,因为模型具有更多功能”这样的想法是不正确的。此外,它违反了像 SRP 这样的基本编程程序。 .

最佳答案

更新

所以评论是:Yes, I know training and serialization utilities exist in Model as I wrote in the question. My question is why TF tutorials need to use Model though they don't use these methods.
在这种情况下,作者可以提供最佳答案,因为您的问题是问他们为什么选择一种方法而不是另一种方法,而他们都可以同样出色地完成工作。为什么可以同样出色地完成工作?嗯,因为 Model is just like a Layer, but with added training and serialization utilities.
我们可以争辩说,当只有层可以完成这项工作时使用模型是一种矫枉过正,但这可能是一个品味问题。

希望能帮助到你

附注。

eager examplecustom layer writing您提供的教程我们不能用层替换模型,因此这些教程不适用于您的问题

使用模型你可以训练,但只有层你不能。请参阅下面的方法列表(不包括内部和继承的方法):
tf.keras.layers.Layer

activity_regularizer
activity_regularizer
add_loss
add_metric
add_update
add_variable
add_weight
apply
build
call
compute_mask
compute_output_shape
count_params
dtype
dynamic
from_config
get_config
get_input_at
get_input_mask_at
get_input_shape_at
get_losses_for
get_output_at
get_output_mask_at
get_output_shape_at
get_updates_for
get_weights
inbound_nodes
input
input_mask
input_shape
losses
metrics
name
non_trainable_variables
non_trainable_weights
outbound_nodes
output
output_mask
output_shape
set_weights
trainable
trainable
trainable_variables
trainable_weights
updates
variables
weights

看?那里没有适合或评估方法。 tf.keras.Model

compile
evaluate
evaluate_generator
fit
fit_generator
get_weights
load_weights
metrics
metrics_names
predict
predict_generator
predict_on_batch
reset_metrics
run_eagerly
run_eagerly
sample_weights
test_on_batch
train_on_batch

关于tensorflow - 即使我们不使用model.fit,我们什么时候应该继承keras.Model而不是keras.layers.Layer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58118334/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com