非类型对象没有属性endwith(Tensorflow)

2024-07-07 06:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个RNN,从莎士比亚文学中生成文本,正如tensorflow课程所教:https://www.tensorflow.org/tutorials/text/text_generation

当我尝试加载权重时,我的程序将崩溃,并显示错误消息:AttributeError:“NoneType”对象没有属性“endswith”

以下是导致程序崩溃的代码行:

model.load_weights(tf.train.latest_checkpoint(check_dir))

这是我的代码的粘贴库:https://pastebin.com/KqmD0phL

以下是完整的错误消息:

Traceback (most recent call last):
  File "D:/Python/PycharmProjects/untitled/Shakespeare.py", line 118, in <module>
    main()
  File "D:/Python/PycharmProjects/untitled/Shakespeare.py", line 108, in main
    model.load_weights(tf.train.latest_checkpoint(check_dir))
  File "C:\Users\marco\venv\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 182, in load_weights
    return super(Model, self).load_weights(filepath, by_name)
  File "C:\Users\marco\venv\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 1335, in load_weights
    if _is_hdf5_filepath(filepath):
  File "C:\Users\marco\venv\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 1645, in _is_hdf5_filepath
    return (filepath.endswith('.h5') or filepath.endswith('.keras') or
AttributeError: 'NoneType' object has no attribute 'endswith'

Tags: inpyvenvlibtensorflowlinesiteload
2条回答

我从不同的教程中得到了同样的问题。据我所知,Tensorflow特定调用和Tensorflow.Keras调用之间似乎存在差异

我在另一篇文章中提到了使用KerasAPI保存和加载KerasAPI,这对我来说很有意义

我希望这有帮助

我用过:

callbacks = [
    tf.keras.callbacks.TensorBoard(log_dir='.'+os.sep+'logs',
                                   histogram_freq=0,  
                                   embeddings_freq=0, 
                                   update_freq='epoch',
                                   profile_batch=0),  
                                   #added this (which doesn't profile) to get the example to to work

    #When saving a model's weights, tf.keras defaults to the checkpoint format. 
    #Pass save_format='h5' to use HDF5 (or pass a filename that ends in .h5).
    tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_prefix,
                                       #save_weights_only=True,
                                       verbose=1),
    PrintLR()
]

然后使用以下命令显式加载模型:

#tutorials indicates to save weights only but I found this to be a problem / concern between 
#tensorflow and keras calls, so save the whole model (who cares anyway)
#model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))

#load the specific model name
model=tf.keras.models.load_model(checkpoint_dir+os.sep+'ckpt_12.h5')


eval_loss, eval_acc = model.evaluate(eval_dataset)

print('Eval loss: {}, Eval Accuracy: {}'.format(eval_loss, eval_acc))

我也遇到了同样的问题。在我的案例中出现此错误消息的原因是包含模型训练检查点的目录的路径无效。所以我建议检查一下这条线

check_dir = './training_checkpoints'

你的代码是正确的。您至少可以尝试将其更改为包含检查点数据的目录的完整路径

check_dir = '/full/path/to/training_checkpoints'

相关问题 更多 >