Keras使用tensorflow后端与烧瓶图错误

时间:2019-06-27 01:49:09

标签: python flask keras

我正在使用Tensorflow在后​​端使用Flask-Python部署Keras InceptionV3模型。麻省理工学院对Places2-Challange数据集进行了训练。代码在Google Colab上工作正常,但现在出现此错误:

on line: features = model_places.predict( img )

ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 162), dtype=float32) is not an element of this graph
def load_model_places():
    global base_model
    base_model = InceptionV3( weights=None , include_top=False )
    x = base_model.output
    x = GlobalAveragePooling2D()( x )
    x = Dense( 1024 , activation='relu' )( x )
    predictions = Dense( 162 , activation='softmax' )( x )
    global model_places
    model_places = Model( inputs=base_model.input , outputs=predictions )
    model_places.load_weights('metadata/places_weights.hdf5')

def prepare_image(image, target_dim):
    if image.mode != "RGB":
        image = image.convert( "RGB" )
    image = image.resize(target_dim)
    image = img_to_array( image )
    image = np.expand_dims( image , axis=0 )
    image = preprocess_input( image )
    return image

def image_pass_places(input_img):
    img_target_size = (224,224)
    img = prepare_image(input_img, img_target_size)
    features = model_places.predict( img )

完整代码:https://github.com/nottahagilani/tagpakistan-deploy-ml/blob/master/app.py

1 个答案:

答案 0 :(得分:0)

是的,当您从带有keras的模型进行预测时,它们是一个错误。由于某些错误,Keras将无法构建图形。尝试借助张量流从模型预测图像。只需替换此行代码

Keras代码:

features = model_places.predict( img )

tensorflow代码:

import tensorflow as tf

graph = tf.get_default_graph()

将此库导入您的代码中并替换。

 with graph.as_default():
    features = model_places.predict( img ).tolist()

如果问题仍未解决:

如果仍然没有解决问题,请尝试刷新图表。

由于您的代码很好,因此在干净的环境中运行应该可以解决它。

清除〜/ .keras /

中的keras缓存

使用正确的软件包在新环境中运行(可以使用anaconda轻松完成)

确保您参加的是全新的会话,keras.backend.clear_session()应该删除所有现有的tf图。

Keras代码:

keras.backend.clear_session()
features = model_places.predict( img )

TensorFlow代码:

import tensorflow as tf
with tf.Session() as sess:
    tf.reset_default_graph()