Search code examples
pythontensorflowjupyter-notebooknlp

What to use in place of predict_classes() in a Jupyter notebook with Tensorflow? (NLP Text Generation)


I am trying to follow a tensorflow NLP tutorial to train a neural network to generate poetry/lyric-like outputs using my own compiled sources. I only know basic python, so this is definitely far above my level of competence. It seems that the tutorial is slightly outdated as I am receiving this error code:

AttributeError: 'Sequential' object has no attribute 'predict_classes'

I understand that the attribute 'predict_classes' is deprecated and no longer used in current versions of tensorflow.

This was a line of code suggested in an answer but I don't understand how to include it into my code:

= np.argmax(model.predict(x_test), axis=-1)

Any help would be appreciated. Here is the section of code that is giving me trouble, along with the error code. I included a link to the full Jupyter notebook as well.

seed_text = "Vernal sunlight"
next_words = 100
  
for _ in range(next_words):
    token_list = tokenizer.texts_to_sequences([seed_text])[0]
    token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
    predicted = model.predict_classes(token_list, verbose=0)
    output_word = ""
    for word, index in tokenizer.word_index.items():
        if index == predicted:
            output_word = word
            break
    seed_text += " " + output_word
print(seed_text)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-0539a42e927b> in <module>()
      5         token_list = tokenizer.texts_to_sequences([seed_text])[0]
      6         token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
----> 7         predicted = model.predict_classes(token_list, verbose=0)
      8         output_word = ""
      9         for word, index in tokenizer.word_index.items():

AttributeError: 'Sequential' object has no attribute 'predict_classes'

Here is the link to the video I was following!

And here is the copy of the Jupyter notebook!


Solution

  • You can find the predicted class by using argmax with the predicted tensor as a parameter. Define predicted as the following :

    predicted = np.argmax(model.predict(x), axis=-1)