TensorFlow中的Keras无法使用config(KeyError:'name')重新初始化顺序模型

时间:2019-06-03 03:40:47

标签: tensorflow serialization keras tf.keras

我建立了一个顺序模型,如下所示:

## build the model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(32, activation='relu', batch_input_shape=(None, 8)))
model.add(tf.keras.layers.Dense(32, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation=None))

现在,我将获取配置并将其用于重新初始化新模型:

## get the config
config = model.get_config()

## re-build the model from config
model2 = tf.keras.Model.from_config(config)

但这会给KeyError: 'name'如下:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-56-1519a2972fdb> in <module>
      9 
     10 ## re-build the model from config
---> 11 model2 = tf.keras.Model.from_config(config)

~/anaconda3/envs/tf2.0/lib/python3.6/site-packages/tensorflow/python/keras/engine/network.py in from_config(cls, config, custom_objects)
   1123     # First, we create all layers and enqueue nodes to be processed
   1124     for layer_data in config['layers']:
-> 1125       process_layer(layer_data)
   1126     # Then we process nodes in order of layer depth.
   1127     # Nodes that cannot yet be processed (if the inbound node

~/anaconda3/envs/tf2.0/lib/python3.6/site-packages/tensorflow/python/keras/engine/network.py in process_layer(layer_data)
   1102           ValueError: In case of improperly formatted `layer_data` dict.
   1103       """
-> 1104       layer_name = layer_data['name']
   1105 
   1106       # Instantiate layer.

KeyError: 'name'

1 个答案:

答案 0 :(得分:2)

您必须对顺序模型使用model2 = tf.keras.Sequential.from_config(config)