Path: blob/master/site/ja/guide/keras/custom_layers_and_models.ipynb
25118 views
Copyright 2020 The TensorFlow Authors.
サブクラス化によるレイヤとモデルの新規作成
MNIST モデルをビルドする
Layer
クラス:状態(重み)といくつかの計算の組み合わせ
Keras の中心的な抽象概念の 1 つは、Layer
クラスです。 レイヤーは、状態(レイヤーの「重み」) と入力から出力への変換 (「呼び出し」、レイヤーのフォワードパス) をカプセル化します。
以下の密に接続されたレイヤーでは、状態は次のとおりです: 変数 w
、b
。
Python 関数のように、レイヤーをテンソル入力で呼び出して使用します。
重み w
および b
をレイヤー属性として設定すると、レイヤーによって自動的に追跡されるので注意してください。
Note you also have access to a quicker shortcut for adding weight to a layer: the add_weight()
method:
Layers can have non-trainable weights
Besides trainable weights, you can add non-trainable weights to a layer as well. Such weights are meant not to be taken into account during backpropagation, when you are training the layer.
Here's how to add and use a non-trainable weight:
It's part of layer.weights
, but it gets categorized as a non-trainable weight:
Best practice: deferring weight creation until the shape of the inputs is known
Our Linear
layer above took an input_dim
argument that was used to compute the shape of the weights w
and b
in __init__()
:
In many cases, you may not know in advance the size of your inputs, and you would like to lazily create weights when that value becomes known, some time after instantiating the layer.
In the Keras API, we recommend creating layer weights in the build(self, inputs_shape)
method of your layer. Like this:
The __call__()
method of your layer will automatically run build the first time it is called. You now have a layer that's lazy and thus easier to use:
上記のように build()
を個別に実装すると、重みの一回の作成とすべての呼び出しでの重みの使用が分離されます。ただし、一部の高度なカスタムレイヤーでは、状態の作成と計算を分離することが非現実的になる可能性があります。レイヤーを実装する際に、重みの作成を最初の __call__()
に延期することができますが、後の呼び出しで同じ重みが使用されるように注意する必要があります。さらに、__call__()
は tf.function
内で初めに実行される可能性が高いため、 __call__()
で作成される変数は tf.init_scope
でラップする必要があります。
Layers are recursively composable
レイヤーインスタンスを別のレイヤーの属性として割り当てると、外部レイヤーは内部レイヤーの重みを追跡し始めます。
__init__()
メソッドでこのようなサブレイヤーを作成し、それを最初の __call__()
で、重みの作成をトリガーすることをお勧めします。
The add_loss()
method
When writing the call()
method of a layer, you can create loss tensors that you will want to use later, when writing your training loop. This is doable by calling self.add_loss(value)
:
These losses (including those created by any inner layer) can be retrieved via layer.losses
. This property is reset at the start of every __call__()
to the top-level layer, so that layer.losses
always contains the loss values created during the last forward pass.
In addition, the loss
property also contains regularization losses created for the weights of any inner layer:
これらの損失は、以下のようにトレーニングループを記述するときに考慮されることを意図しています。
For a detailed guide about writing training loops, see the guide to writing a training loop from scratch.
These losses also work seamlessly with fit()
(they get automatically summed and added to the main loss, if any):
add_metric()
メソッド
add_loss()
と同様に、レイヤーではadd_metric()
メソッドでトレーニング中の数量の移動平均を追跡できます。
「ロジスティックエンドポイント」レイヤーでは、入力として予測とターゲットを受け取り、 add_loss()
を介して追跡する損失を計算し、add_metric()
を介して追跡する精度スカラーを計算します。
Metrics tracked in this way are accessible via layer.metrics
:
Just like for add_loss()
, these metrics are tracked by fit()
:
You can optionally enable serialization on your layers
If you need your custom layers to be serializable as part of a Functional model, you can optionally implement a get_config()
method:
Note that the __init__()
method of the base Layer
class takes some keyword arguments, in particular a name
and a dtype
. It's good practice to pass these arguments to the parent class in __init__()
and to include them in the layer config:
If you need more flexibility when deserializing the layer from its config, you can also override the from_config()
class method. This is the base implementation of from_config()
:
To learn more about serialization and saving, see the complete guide to saving and serializing models.
Privileged training
argument in the call()
method
Some layers, in particular the BatchNormalization
layer and the Dropout
layer, have different behaviors during training and inference. For such layers, it is standard practice to expose a training
(boolean) argument in the call()
method.
By exposing this argument in call()
, you enable the built-in training and evaluation loops (e.g. fit()
) to correctly use the layer in training and inference.
Privileged mask
argument in the call()
method
The other privileged argument supported by call()
is the mask
argument.
You will find it in all Keras RNN layers. A mask is a boolean tensor (one boolean value per timestep in the input) used to skip certain input timesteps when processing timeseries data.
Keras will automatically pass the correct mask
argument to __call__()
for layers that support it, when a mask is generated by a prior layer. Mask-generating layers are the Embedding
layer configured with mask_zero=True
, and the Masking
layer.
To learn more about masking and how to write masking-enabled layers, please check out the guide "understanding padding and masking".
モデル
クラス
一般的に、レイヤー
クラスを使用して内部計算ブロックを定義し、モデル
クラスを使用して外部モデル(トレーニングするオブジェクト)を定義します。
たとえば、ResNet50モデルでは、レイヤー
をサブクラス化する複数のResNetブロックと、ResNet50ネットワーク全体を包含する1つの モデル
があります。
モデル
クラスはレイヤー
クラスと同じAPIをもちますが、以下の点で異なります。
組み込みのトレーニング、評価、予測ループを公開します(
model.fit()
、model.evaluate()
,、model.predict()
)。model.layers
プロパティを介して、その内部レイヤーのリストを公開します。保存およびシリアル化APIを公開します(
save()
、save_weights()
...)
実質的にレイヤー
クラスは、文献で「レイヤー」(「畳み込みレイヤー」または「リカレントレイヤー」など)または「ブロック」(「ResNetブロック」または「Inceptionブロック」など)と呼ばれているものに対応します。
一方、モデル
クラスは、文献で「モデル」(「ディープラーニングモデル」など)または「ネットワーク」(「ディープニューラルネットワーク」など)と呼ばれているものに対応します 。
Layer
クラスまたはModel
クラスのどちらを使用すべきか迷っている場合は、次の点を確認してください。 fit()
やsave()
を呼び出す必要がある場合は、Model
を使用してください。 そうでない場合(クラスがより大きなシステムの単なるブロックである場合や自分でトレーニングを記述してコードを保存する場合)Layer
を使用します。
たとえば、上のmini-resnetの例を使用してModel
を構築し、fit()
でトレーニングし、save_weights()
で保存できます。
Putting it all together: an end-to-end example
Here's what you've learned so far:
A
Layer
encapsulate a state (created in__init__()
orbuild()
) and some computation (defined incall()
).Layers can be recursively nested to create new, bigger computation blocks.
Layers can create and track losses (typically regularization losses) as well as metrics, via
add_loss()
andadd_metric()
The outer container, the thing you want to train, is a
Model
. AModel
is just like aLayer
, but with added training and serialization utilities.
Let's put all of these things together into an end-to-end example: we're going to implement a Variational AutoEncoder (VAE). We'll train it on MNIST digits.
Our VAE will be a subclass of Model
, built as a nested composition of layers that subclass Layer
. It will feature a regularization loss (KL divergence).
Let's write a simple training loop on MNIST:
Note that since the VAE is subclassing Model
, it features built-in training loops. So you could also have trained it like this:
Beyond object-oriented development: the Functional API
Was this example too much object-oriented development for you? You can also build models using the Functional API. Importantly, choosing one style or another does not prevent you from leveraging components written in the other style: you can always mix-and-match.
For instance, the Functional API example below reuses the same Sampling
layer we defined in the example above:
For more information, make sure to read the Functional API guide.