打开使用Tensorflow后端的Keras模型时出现NameError

时间:2017-06-18 23:51:51

标签: python tensorflow keras

我想在我的第一个Keras图层中调整输入图像的大小,所以我跟着this问题。解决方案工作得很好,直到我保存我的模型,然后尝试在另一个文件中使用它并抛出

NameError: name 'ktf' is not defined

我尝试添加:

from keras.backend import tf as ktf

打开模型的文件,但它仍然无法在模型中识别它。我需要做什么才能打开保存模型的程序识别tensorflow后端使用的函数?

更多细节......

train.py:

from keras.backend import tf as ktf

#Other stuff...

model = Sequential()
model.add(Lambda(lambda x: ktf.image.resize_images(x, (80, 160)), input_shape=(160, 320, 3))) #This line referenced in error

#Rest of model and training...

model.save('model.h5')

eval.py:

from keras.backend import tf as ktf

#Other stuff...

model = load_model('model.h5') #Error is here

错误讯息:

Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\program\eval.py", line 1
38, in <module>
    model = load_model('model.h5')
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\models.py", line 246,
 in load_model
    model = model_from_config(model_config, custom_objects=custom_objects)
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\models.py", line 314,
 in model_from_config
    return layer_module.deserialize(config, custom_objects=custom_objects)
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\layers\__init__.py",
line 54, in deserialize
    printable_module_name='layer')
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\utils\generic_utils.p
y", line 140, in deserialize_keras_object
    list(custom_objects.items())))
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\models.py", line 1217
, in from_config
    model.add(layer)
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\models.py", line 443,
 in add
    layer(x)
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\engine\topology.py",
line 596, in __call__
    output = self.call(inputs, **kwargs)
  File "C:\Program Files\Anaconda3\lib\site-packages\keras\layers\core.py", line
 652, in call
    return self.function(inputs, **arguments)
  File "train.py", line 189, in <lambda>
    model.add(Lambda(lambda x: ktf.image.resize_images(x, (80, 160)), input_shape=(160, 320, 3)))
NameError: name 'ktf' is not defined

2 个答案:

答案 0 :(得分:4)

解决方案是所描述的解决方法,即将后端导入为&#39; k&#39;:

train.py:

from keras import backend as K

#Other stuff...

model = Sequential()
model.add(Lambda(lambda x: K.tf.image.resize_images(x, (80, 160)), \
                 input_shape=(160, 320, 3))) #Resize 80x160x3

#Rest of model and training...

model.save('model.h5')

eval.py:

from keras import backend as K

#Other stuff...

model = load_model('model.h5') #Error is here

答案 1 :(得分:0)

我知道我迟到了三年半,但是如果您已经保存了模型并且无法更改生成代码,您可以像这样将丢失的对象传递给 load_model

from tf.keras import backend
from tf.keras.models import load_model
model = load_model("yourmodel.h5", custom_objects={"backend": backend})