Keras in TensorFlow cannot reinitialize a sequential model using config (KeyError: 'name')

Keras in TensorFlow cannot reinitialize a sequential model using config (KeyError: 'name')

我构建了一个顺序模型如下:

## 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'

您必须将 model2 = tf.keras.Sequential.from_config(config) 与顺序模型一起使用