From 8360ef3a5af9ddf517177bdc0311ae7b032ff35f Mon Sep 17 00:00:00 2001 From: Matt Gardner Date: Mon, 7 Nov 2016 18:19:27 -0800 Subject: [PATCH] Add documentation to set self.built = True in MyLayer.build() (#4315) * Added documentation to set self.built = True in MyLayer.build() * Update writing-your-own-keras-layers.md --- docs/templates/layers/writing-your-own-keras-layers.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/templates/layers/writing-your-own-keras-layers.md b/docs/templates/layers/writing-your-own-keras-layers.md index b6c093744..9f1838ba6 100644 --- a/docs/templates/layers/writing-your-own-keras-layers.md +++ b/docs/templates/layers/writing-your-own-keras-layers.md @@ -4,7 +4,7 @@ For simple, stateless custom operations, you are probably better off using `laye Here is the skeleton of a Keras layer. There are only three methods you need to implement: -- `build(input_shape)`: this is where you will define your weights. Trainable weights should be added to the list `self.trainable_weights`. Other attributes of note are: `self.non_trainable_weights` (list) and `self.updates` (list of update tuples (tensor, new_tensor)). For an example of how to use `non_trainable_weights` and `updates`, see the code for the `BatchNormalization` layer. +- `build(input_shape)`: this is where you will define your weights. Trainable weights should be added to the list `self.trainable_weights`. Other attributes of note are: `self.non_trainable_weights` (list) and `self.updates` (list of update tuples (tensor, new_tensor)). For an example of how to use `non_trainable_weights` and `updates`, see the code for the `BatchNormalization` layer. This method must set `self.built = True`, which can be done by calling `super([Layer], self).build()`. - `call(x)`: this is where the layer's logic lives. Unless you want your layer to support masking, you only have to care about the first argument passed to `call`: the input tensor. - `get_output_shape_for(input_shape)`: in case your layer modifies the shape of its input, you should specify here the shape transformation logic. This allows Keras to do automatic shape inference. @@ -23,6 +23,7 @@ class MyLayer(Layer): initial_weight_value = np.random.random((input_dim, output_dim)) self.W = K.variable(initial_weight_value) self.trainable_weights = [self.W] + super(MyLayer, self).build() # be sure you call this somewhere! def call(self, x, mask=None): return K.dot(x, self.W) @@ -31,4 +32,4 @@ class MyLayer(Layer): return (input_shape[0], self.output_dim) ``` -The existing Keras layers provide ample examples of how to implement almost anything. Never hesitate to read the source code! \ No newline at end of file +The existing Keras layers provide ample examples of how to implement almost anything. Never hesitate to read the source code!