What is the 'clone_model' function in Keras? Why is it used?
A clone mode is a model that reproduces the behavior of the original model, where we can input new tensors, with new weights to the layers. The cloned models behave differently if we customize the cloned model or we use the custom clone_function.
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import UpSampling2D
We will make a model to clone.
# define input data
X = np.array([10, 6, 3, 20])
# show input data for context
print(X)
# reshape input data into one sample a sample with a channel
X = X.reshape((1, 2, 2, 1))
# define model
model = Sequential()
model.add(UpSampling2D(input_shape=(2, 2, 1)))
model.summary()
[10 6 3 20] Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= up_sampling2d (UpSampling2D) (None, 4, 4, 1) 0 ================================================================= Total params: 0 Trainable params: 0 Non-trainable params: 0 _________________________________________________________________
#cloning of model
model_copy= keras.models.clone_model(model)
model_copy.build((None, 5)) # replace 10 with number of variables in input layer
model_copy.compile(optimizer='adam', loss='categorical_crossentropy')
model_copy.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= up_sampling2d (UpSampling2D) (None, 4, 4, 1) 0 ================================================================= Total params: 0 Trainable params: 0 Non-trainable params: 0 _________________________________________________________________