text
stringlengths 0
4.99k
|
---|
Functional model example: |
inputs = keras.Input((32,)) |
outputs = keras.layers.Dense(1)(inputs) |
model = keras.Model(inputs, outputs) |
config = model.get_config() |
new_model = keras.Model.from_config(config) |
to_json() and tf.keras.models.model_from_json() |
This is similar to get_config / from_config, except it turns the model into a JSON string, which can then be loaded without the original model class. It is also specific to models, it isn't meant for layers. |
Example: |
model = keras.Sequential([keras.Input((32,)), keras.layers.Dense(1)]) |
json_config = model.to_json() |
new_model = keras.models.model_from_json(json_config) |
Custom objects |
Models and layers |
The architecture of subclassed models and layers are defined in the methods __init__ and call. They are considered Python bytecode, which cannot be serialized into a JSON-compatible config -- you could try serializing the bytecode (e.g. via pickle), but it's completely unsafe and means your model cannot be loaded on a different system. |
In order to save/load a model with custom-defined layers, or a subclassed model, you should overwrite the get_config and optionally from_config methods. Additionally, you should use register the custom object so that Keras is aware of it. |
Custom functions |
Custom-defined functions (e.g. activation loss or initialization) do not need a get_config method. The function name is sufficient for loading as long as it is registered as a custom object. |
Loading the TensorFlow graph only |
It's possible to load the TensorFlow graph generated by the Keras. If you do so, you won't need to provide any custom_objects. You can do so like this: |
model.save("my_model") |
tensorflow_graph = tf.saved_model.load("my_model") |
x = np.random.uniform(size=(4, 32)).astype(np.float32) |
predicted = tensorflow_graph(x).numpy() |
INFO:tensorflow:Assets written to: my_model/assets |
Note that this method has several drawbacks: * For traceability reasons, you should always have access to the custom objects that were used. You wouldn't want to put in production a model that you cannot re-create. * The object returned by tf.saved_model.load isn't a Keras model. So it's not as easy to use. For example, you won't have access to .predict() or .fit() |
Even if its use is discouraged, it can help you if you're in a tight spot, for example, if you lost the code of your custom objects or have issues loading the model with tf.keras.models.load_model(). |
You can find out more in the page about tf.saved_model.load |
Defining the config methods |
Specifications: |
get_config should return a JSON-serializable dictionary in order to be compatible with the Keras architecture- and model-saving APIs. |
from_config(config) (classmethod) should return a new layer or model object that is created from the config. The default implementation returns cls(**config). |
Example: |
class CustomLayer(keras.layers.Layer): |
def __init__(self, a): |
self.var = tf.Variable(a, name="var_a") |
def call(self, inputs, training=False): |
if training: |
return inputs * self.var |
else: |
return inputs |
def get_config(self): |
return {"a": self.var.numpy()} |
# There's actually no need to define `from_config` here, since returning |
# `cls(**config)` is the default behavior. |
@classmethod |
def from_config(cls, config): |
return cls(**config) |
layer = CustomLayer(5) |
layer.var.assign(2) |
serialized_layer = keras.layers.serialize(layer) |
new_layer = keras.layers.deserialize( |
serialized_layer, custom_objects={"CustomLayer": CustomLayer} |
) |
Registering the custom object |
Keras keeps a note of which class generated the config. From the example above, tf.keras.layers.serialize generates a serialized form of the custom layer: |
{'class_name': 'CustomLayer', 'config': {'a': 2}} |
Keras keeps a master list of all built-in layer, model, optimizer, and metric classes, which is used to find the correct class to call from_config. If the class can't be found, then an error is raised (Value Error: Unknown layer). There are a few ways to register custom classes to this list: |
Setting custom_objects argument in the loading function. (see the example in section above "Defining the config methods") |
tf.keras.utils.custom_object_scope or tf.keras.utils.CustomObjectScope |
tf.keras.utils.register_keras_serializable |
Custom layer and function example |
class CustomLayer(keras.layers.Layer): |
def __init__(self, units=32, **kwargs): |
super(CustomLayer, self).__init__(**kwargs) |
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 |
) |