2017-06-18 94 views
-2

我想调整我的输入图像在我的第一个Keras层,所以我跟着this SO问题。解决办法伟大的工作,直到我救了我的模型,然后试图在另一个文件中使用它,它抛出NameError当打开使用Tensorflow后端Keras模型

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 
+0

是否安装tensorflow在单独的环境(VirtualEnv/Anaconda)?如果没有,你确定tensorflow是否安装? (运行'pip install tensorflow') –

+0

是的,安装了tf,我可以在同一台机器上训练。此外,该错误不在tf后端的导入处,而是在模型的加载处。这个问题实际上是'ktf'别名不被eval.py认可 – DrTarr

+0

实际上,这似乎是一个已知问题,在链接的SO问题的注释中以及类似的[here](https:// github)中都有描述。 COM/fchollet/keras /问题/ 4609)。看起来像导入后端,'K'可以解决我的问题,但是,我需要保留该模型。 – DrTarr

回答

1

溶液作为介绍的解决方法,这是导入后端为 'K':

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