Search code examples
pythontensorflowmachine-learningkerasprediction

keras unable to call model.predict_classes for multiple times


def predictOne(imgPath):

    model = load_model("withImageMagic.h5")
    image = read_image(imgPath)
    test_sample = preprocess(image)
    predicted_class = model.predict_classes(([test_sample]))
    return predicted_class

I have already trained a model. In this function, I load my model, read a new image, do some preprocessing and finally predict its label.

When I run my main.py file, this function is called and everything goes smoothly. However, after a couple of seconds, this function will be called again with another image and I get this error:

'Cannot interpret feed_dict key as Tensor: ' + e.args[0])

TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(5, 5, 1, 32), dtype=float32) is not an element of this graph.

It's very strange that the function only works the first time. I tested multiple images and got the same behavior.

Windows 10 - tensorflow-gpu with keras


Solution

  • Try loading model from file outside the function, and give the model object as argument to the function def predictOne(imgPath, model). This will also be much faster, since the weights don't need to be loaded from disk every time a prediction is needed.

    If you want to keep loading model inside the function, import the backend:

    from keras import backend as K
    

    and then

    K.clear_session() 
    

    before loading the model.