简体   繁体   English

如何将保存的 model 转换或加载到 TensorFlow 或 Keras?

[英]How to convert or load saved model into TensorFlow or Keras?

I used tensorflow keras to create a model and defined a callback to save the model after each epoch.我使用 tensorflow keras 创建了一个 model 并定义了一个回调来保存每个 Z20F35E630DAF439DBFA4C3F6Depoch58CZ 之后的回调。 It worked and saved the model in pb format but I cannot load it again into keras because keras just accept h5 format.它工作并以pb格式保存了 model 但我无法将其再次加载到 keras 因为 keras 只接受h5格式。

I have two questions:我有两个问题:

  • Except tensorflow serving how I can load my saved model into keras/tensorflow?除了 tensorflow 服务之外,我如何将保存的 model 加载到 keras/tensorflow 中?
  • How I can save a keras model after each epoch in h5 format?如何在每个时期后以h5格式保存 keras model ?

My callback and saving the model:我的回调并保存 model:

from tensorflow.keras.callbacks import ModelCheckpoint

cp_callback = ModelCheckpoint(filepath=checkpoint_path, save_freq= 'epoch', verbose=1 )

regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
regressor.fit(X_train, y_train, epochs = 10, batch_size = 32, callbacks=[cp_callback])

My saved model structure:我保存的 model 结构:

saved_trained_10_epochs
├── assets
├── saved_model.pb
└── variables
    ├── variables.data-00000-of-00001
    └── variables.index

Update更新

I tried to use latest_checkpoint as below but got below errors:我尝试使用latest_checkpoint如下,但出现以下错误:

from tensorflow.train import latest_checkpoint

loaded_model = latest_checkpoint(checkpoint_path)
loaded_model.summary()

The error:错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-57-76a8ebe4f259> in <module>
----> 1 loaded_model.summary()

AttributeError: 'NoneType' object has no attribute 'summary'

And after recreating the model:在重新创建 model 之后:

loaded_regressor = Sequential()

loaded_regressor.add(LSTM(units = 180, return_sequences = True, input_shape = (X_train.shape[1], 3)))
loaded_regressor.add(Dropout(0.2))

loaded_regressor.add(LSTM(units = 180, return_sequences = True))
loaded_regressor.add(Dropout(0.2))

loaded_regressor.add(LSTM(units = 180, return_sequences = True))
loaded_regressor.add(Dropout(0.2))

loaded_regressor.add(LSTM(units = 180, return_sequences = True))
loaded_regressor.add(Dropout(0.2))

loaded_regressor.add(LSTM(units = 180, return_sequences = True))
loaded_regressor.add(Dropout(0.2))

loaded_regressor.add(LSTM(units = 180))
loaded_regressor.add(Dropout(0.2))

loaded_regressor.add(Dense(units = 1))

loaded_regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
loaded_regressor.load_weights(latest_checkpoint(checkpoint_path))

The error:错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-30-c344f1759d01> in <module>
     22 
     23 loaded_regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
---> 24 loaded_regressor.load_weights(latest_checkpoint(checkpoint_path))

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in load_weights(self, filepath, by_name)
    160         raise ValueError('Load weights is not yet supported with TPUStrategy '
    161                          'with steps_per_run greater than 1.')
--> 162     return super(Model, self).load_weights(filepath, by_name)
    163 
    164   @trackable.no_automatic_dependency_tracking

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in load_weights(self, filepath, by_name)
   1375             format.
   1376     """
-> 1377     if _is_hdf5_filepath(filepath):
   1378       save_format = 'h5'
   1379     else:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in _is_hdf5_filepath(filepath)
   1670 
   1671 def _is_hdf5_filepath(filepath):
-> 1672   return (filepath.endswith('.h5') or filepath.endswith('.keras') or
   1673           filepath.endswith('.hdf5'))
   1674 

AttributeError: 'NoneType' object has no attribute 'endswith'

tf.keras models are loaded using tf.keras.models.load_model , this should work fine as tf.keras supports reading/writing multiple formats, including tensorflow checkpoints. tf.keras models are loaded using tf.keras.models.load_model , this should work fine as tf.keras supports reading/writing multiple formats, including tensorflow checkpoints.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM