python - 在加载 Keras 保存模型时,是否有人得到 "AttributeError: ' str' 对象没有属性 'decode'"

标签 python machine-learning keras deep-learning

训练后,我使用

保存了 Keras 的整个模型和唯一的权重
model.save_weights(MODEL_WEIGHTS) and model.save(MODEL_NAME)

模型和权重保存成功,没有报错。 我可以简单地使用 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'

我从来没有收到过这个错误,我曾经成功地加载过任何模型。我正在使用带有 tensorflow 后端的 Keras 2.2.4。 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()

最佳答案

对我来说,解决方案是降级 h5py 包(在我的例子中是 2.10.0),显然仅将 Keras 和 Tensorflow 恢复到正确的版本是不够的。

关于python - 在加载 Keras 保存模型时,是否有人得到 "AttributeError: ' str' 对象没有属性 'decode'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740577/

相关文章:

php - 命令行命令在Python中不起作用-不发送文件

java - 如何将 MLlib Apache Spark 库安装到 JAVA Eclpise 项目中?

python - 使用 Python 和 win32com 从 Outlook 检索电子邮件时突然出错

python - 如何在数据 block 集群上运行非 Spark 代码?

apache-spark - Spark ML - MulticlassClassificationEvaluator - 我们可以通过每个类标签获得精度/召回率吗?

python - 使用 tf Estimator 和 export_savedmodel 函数导出模型

python - keras 中的 1d CNN 音频

python - 将输入数据作为数组传递时,请勿指定 `steps_per_epoch`/`steps` 参数。请使用 `batch_size` 代替

Python:keras 形状不匹配错误

python - 如何在 Python 列表列表中找到项目的位置?