I am trying to use the "layer_from_config" Keras utilty to load layers from previously saved configurations, as described in: https://keras.io/layers/about-keras-layers/
For starters, I'm trying to use it on a basic model
import keras
keras.backend.set_image_dim_ordering("th")
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
# dimensions of our images.
img_width, img_height = 150, 150
train_data_dir = '//shared_directory/projects/try_CD/data/train/'
validation_data_dir = '//shared_directory/projects/try_CD/data/validation'
nb_train_samples = 2000
nb_validation_samples = 800
nb_epoch = 50 # 50
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(3, img_width, img_height)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
from keras.utils.layer_utils import layer_from_config
config = model.layers[1].get_config()
layer = layer_from_config(config)
As expected, config
returns a dict type object, and printing it reads
{'activation': 'relu', 'trainable': True, 'name': 'activation_1'}
However, when I run the code above I'm getting the following error message
Traceback (most recent call last):
File "keras_CvD.py", line 91, in <module>
layer = layer_from_config(config)
File "/usr/local/lib/python2.7/dist-packages/keras/utils/layer_utils.py", line 26, in layer_from_config
class_name = config['class_name']
KeyError: 'class_name'
So, what am I doing wrong?
Ok this is a weird case, maybe coming from an update. Here is the way it's working :
if you print(model.layers[1].get_config())
:
{'trainable': True, 'name': 'activation_1', 'activation': 'relu'}
if you print(model.get_config()[1])
:
{'config': {'trainable': True, 'name': 'activation_1', 'activation': 'relu'}, 'class_name': 'Activation'}
So the model.get_config()
is the one containing a list of dictionnaries that layer_from_config()
will accept.
Instead of getting the list of layers and then its config which is in a "bad" format, you have to get the model config which is a list of layers config with the right format.
Their doc isn't up to date it seems. Either they should adapt it, or they should adapt the code of layer.get_config()
.
Anyway, you can use it now :)