2017-06-18 92 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