0
$\begingroup$

I saved my keras model into .h5 format. Again I've loaded that .h5 file into my colab and tried to predict with that model. model.save("/content/drive/My Drive/Datasets/sentiment_analysis.h5")

from keras.models import load_model
loaded_model = load_model("/content/drive/MyDrive/Datasets/sentiment_analysis.h5")
loaded_model.predict("i love machine learning and google")

It's giving error list index out of range.

IndexError: list index out of range
$\endgroup$
1

3 Answers 3

1
$\begingroup$

I think the error might be caused because you are giving a plain text as input to your model. While preparing a model and training it, I usually use a tokenizer from keras.preprocessing.text.Tokenizer and after the training session I save the tokenizer as a .pkl file. You can then load the tokenizer along with your model and feed the already trained tokenizer with your text, and after all this process you can give as input to your model the tokenized text. Example:

from keras.models import load_model
loaded_model = load_model("model.h5")
tokenizer = pickle.load(open('tokenizer.pickle', 'rb'))
text = "i love machine learning and google"
token = tokenizer.texts_to_sequences([text])
# you should make the proper padding before prediction
token = keras.preprocessing.sequence.pad_sequences(text, maxlen=250)
loaded_model.predict(text)
$\endgroup$
0
$\begingroup$

Try these:

  1. import everything from tensorflow keras API.
  2. tf.keras.models.load_model("./saved_models/our_model.h5", compile=False) (make sure you have model and weights both in the file)
$\endgroup$
2
  • $\begingroup$ it's not working. I'm doing this model.save(KERAS_MODEL) w2v_model.save(WORD2VEC_MODEL) pickle.dump(tokenizer, open(TOKENIZER_MODEL, "wb"), protocol=0) pickle.dump(encoder, open(ENCODER_MODEL, "wb"), protocol=0) and loading the keras_model file $\endgroup$ Aug 5, 2020 at 14:22
  • $\begingroup$ i have 4 files. encoder.pkl, model.h5, model.w2v and tokenizer.pkl but i'm loading only model.h5 and trying to predict $\endgroup$ Aug 5, 2020 at 14:25
0
$\begingroup$

The predict function in Keras expects batches of inputs. If your input is a single text, you need to add an axis at the beginning of the tensor.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.