加载Keras保存的模型时,是否有人得到“ AttributeError:'str'对象没有属性'decode'”?

Riz*_*wan 5 python machine-learning deep-learning keras

训练后,我使用以下命令保存了Keras整个模型和Only Weights

model.save_weights(MODEL_WEIGHTS) and model.save(MODEL_NAME)
Run Code Online (Sandbox Code Playgroud)

模型和权重已成功保存,没有错误。我可以简单地使用model.load_weights成功加载权重,它们很不错,但是当我尝试通过load_model加载保存模型时,出现了错误。

File "C:/Users/Rizwan/model_testing/model_performance.py", line 46, in <module>
Model2 = load_model('nasnet_RS2.h5',custom_objects={'euc_dist_keras': euc_dist_keras})
File "C:\Users\Rizwan\AppData\Roaming\Python\Python36\site-packages\keras\engine\saving.py", line 419, in load_model
model = _deserialize_model(f, custom_objects, compile)
File "C:\Users\Rizwan\AppData\Roaming\Python\Python36\site-packages\keras\engine\saving.py", line 321, in _deserialize_model
optimizer_weights_group['weight_names']]
File "C:\Users\Rizwan\AppData\Roaming\Python\Python36\site-packages\keras\engine\saving.py", line 320, in <listcomp>
n.decode('utf8') for n in
AttributeError: 'str' object has no attribute 'decode'
Run Code Online (Sandbox Code Playgroud)

我从未收到此错误,我曾经成功加载任何模型。我正在将Keras 2.2.4与tensorflow后端一起使用。Python 3.6。我的培训准则是:

from keras_preprocessing.image import ImageDataGenerator
from keras import backend as K
from keras.models import load_model
from keras.callbacks import ReduceLROnPlateau, TensorBoard, 
ModelCheckpoint,EarlyStopping
import pandas as pd

MODEL_NAME = "nasnet_RS2.h5"
MODEL_WEIGHTS = "nasnet_RS2_weights.h5"
def euc_dist_keras(y_true, y_pred):
return K.sqrt(K.sum(K.square(y_true - y_pred), axis=-1, keepdims=True))
def main():

# Here, we initialize the "NASNetMobile" model type and customize the final 
#feature regressor layer.
# NASNet is a neural network architecture developed by Google.
# This architecture is specialized for transfer learning, and was discovered via Neural Architecture Search.
# NASNetMobile is a smaller version of NASNet.
model = NASNetMobile()
model = Model(model.input, Dense(1, activation='linear', kernel_initializer='normal')(model.layers[-2].output))

#    model = load_model('current_best.hdf5', custom_objects={'euc_dist_keras': euc_dist_keras})

# This model will use the "Adam" optimizer.
model.compile("adam", euc_dist_keras)
lr_callback = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.003)
# This callback will log model stats to Tensorboard.
tb_callback = TensorBoard()
# This callback will checkpoint the best model at every epoch.
mc_callback = ModelCheckpoint(filepath='current_best_mem3.h5', verbose=1, save_best_only=True)
es_callback=EarlyStopping(monitor='val_loss', min_delta=0, patience=4, verbose=0, mode='auto', baseline=None, restore_best_weights=True)

# This is the train DataSequence.
# These are the callbacks.
#callbacks = [lr_callback, tb_callback,mc_callback]
callbacks = [lr_callback, tb_callback,es_callback]

train_pd = pd.read_csv("./train3.txt", delimiter=" ", names=["id", "label"], index_col=None)
test_pd = pd.read_csv("./val3.txt", delimiter=" ", names=["id", "label"], index_col=None)

 #    train_pd = pd.read_csv("./train2.txt",delimiter=" ",header=None,index_col=None)
 #    test_pd = pd.read_csv("./val2.txt",delimiter=" ",header=None,index_col=None)
#model.summary()
batch_size=32
datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = datagen.flow_from_dataframe(dataframe=train_pd, 
directory="./images", x_col="id", y_col="label",
                                              has_ext=True, 
class_mode="other", target_size=(224, 224),
                                              batch_size=batch_size)
valid_generator = datagen.flow_from_dataframe(dataframe=test_pd, directory="./images", x_col="id", y_col="label",
                                              has_ext=True, class_mode="other", target_size=(224, 224),
                                              batch_size=batch_size)

STEP_SIZE_TRAIN = train_generator.n // train_generator.batch_size
STEP_SIZE_VALID = valid_generator.n // valid_generator.batch_size
model.fit_generator(generator=train_generator,
                    steps_per_epoch=STEP_SIZE_TRAIN,
                    validation_data=valid_generator,
                    validation_steps=STEP_SIZE_VALID,
                    callbacks=callbacks,
                    epochs=20)

# we save the model.
model.save_weights(MODEL_WEIGHTS)
model.save(MODEL_NAME)
if __name__ == '__main__':
   # freeze_support() here if program needs to be frozen
    main()
Run Code Online (Sandbox Code Playgroud)

arn*_*o_v 113

对我来说,解决方案是将h5py包降级(在我的情况下是 2.10.0),显然仅将 Keras 和 Tensorflow 放回正确的版本是不够的。

  • 有关此问题的更多信息:https://github.com/tensorflow/tensorflow/issues/44467 (4认同)
  • 从 alexhg 的链接来看,“我们将来会有人致力于让 TF 与 h5py &gt;= 3 一起工作,但这只会在 TF 2.5 或更高版本中出现。”出现这个问题是因为 TensorFlow 无法与 h5py v3 一起工作,并且较新。2.10.0是最新版本-2.xy (3认同)

She*_*kar 56

我使用以下命令降级了我的 h5py 包,

pip install 'h5py==2.10.0' --force-reinstall
Run Code Online (Sandbox Code Playgroud)

重新启动我的 ipython 内核,它工作正常。

  • 由于缺少 RECORD 文件,使用这个确切的命令会导致 OSError。使用 `conda install 'h5py==2.10.0'` 可以。 (4认同)

Ibr*_*bra 14

对我来说,是h5py的版本优于我之前的版本。
通过设置来修复它2.10.0


Cod*_*ker 12

使用以下命令降级 h5py 包来解决问题,

pip install h5py==2.10.0 --force-reinstall
Run Code Online (Sandbox Code Playgroud)


小智 6

使用 TF 格式文件而不是 h5py 保存:save_format='tf'。就我而言:

model.save_weights("NMT_model_weight.tf",save_format='tf')
Run Code Online (Sandbox Code Playgroud)


小智 5

我遇到了同样的问题,解决了compile=False输入load_model

model_ = load_model('path to your model.h5',custom_objects={'Scale': Scale()}, compile=False)
sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)
model_.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)

  • 无论如何,`compile = False`给了我这个错误,`File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/ saving.py", line 229, in load_model model_config = json.loads(model_config.decode('utf-8')) AttributeError: 'str' 对象没有属性 'decode'` (2认同)
  • 这没有帮助。 (2认同)