text
stringlengths
0
4.99k
text_input_b = keras.Input(shape=(None,), dtype="int32")
# Reuse the same layer to encode both inputs
encoded_input_a = shared_embedding(text_input_a)
encoded_input_b = shared_embedding(text_input_b)
Extract and reuse nodes in the graph of layers
Because the graph of layers you are manipulating is a static data structure, it can be accessed and inspected. And this is how you are able to plot functional models as images.
This also means that you can access the activations of intermediate layers ("nodes" in the graph) and reuse them elsewhere -- which is very useful for something like feature extraction.
Let's look at an example. This is a VGG19 model with weights pretrained on ImageNet:
vgg19 = tf.keras.applications.VGG19()
And these are the intermediate activations of the model, obtained by querying the graph data structure:
features_list = [layer.output for layer in vgg19.layers]
Use these features to create a new feature-extraction model that returns the values of the intermediate layer activations:
feat_extraction_model = keras.Model(inputs=vgg19.input, outputs=features_list)
img = np.random.random((1, 224, 224, 3)).astype("float32")
extracted_features = feat_extraction_model(img)
This comes in handy for tasks like neural style transfer, among other things.
Extend the API using custom layers
tf.keras includes a wide range of built-in layers, for example:
Convolutional layers: Conv1D, Conv2D, Conv3D, Conv2DTranspose
Pooling layers: MaxPooling1D, MaxPooling2D, MaxPooling3D, AveragePooling1D
RNN layers: GRU, LSTM, ConvLSTM2D
BatchNormalization, Dropout, Embedding, etc.
But if you don't find what you need, it's easy to extend the API by creating your own layers. All layers subclass the Layer class and implement:
call method, that specifies the computation done by the layer.
build method, that creates the weights of the layer (this is just a style convention since you can create weights in __init__, as well).
To learn more about creating layers from scratch, read custom layers and models guide.
The following is a basic implementation of tf.keras.layers.Dense:
class CustomDense(layers.Layer):
def __init__(self, units=32):
super(CustomDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)
For serialization support in your custom layer, define a get_config method that returns the constructor arguments of the layer instance:
class CustomDense(layers.Layer):
def __init__(self, units=32):
super(CustomDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
def get_config(self):
return {"units": self.units}
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)
config = model.get_config()
new_model = keras.Model.from_config(config, custom_objects={"CustomDense": CustomDense})
Optionally, implement the class method from_config(cls, config) which is used when recreating a layer instance given its config dictionary. The default implementation of from_config is:
def from_config(cls, config):
return cls(**config)
When to use the functional API
Should you use the Keras functional API to create a new model, or just subclass the Model class directly? In general, the functional API is higher-level, easier and safer, and has a number of features that subclassed models do not support.