I am attempting to do a text generation program using Keras and Tensorflow. I have come across the problem while trying to use the predict_classes. After a quick research, I learnt that the predict_classes has been removed in the new Tensorflow version, but I have not received any satisfactory solution. My code is given below:
def generate_text_seq(model, tokenizer, text_seq_length, seed_text, n_words):
text = []
for _ in range(n_words):
encoded = tokenizer.texts_to_sequences([seed_text])[0]
encoded = pad_sequences([encoded], maxlen = text_seq_length, truncating = 'pre')
y_pred = model.predict_classes(encoded)
predicted_word = ''
for word, index in tokenizer.word_index.items():
if index == y_pred.any():
predicted_word = word
break
seed_text = seed_text + ' ' + predicted_word
text.append(predicted_word)
return ' '.join(text)
The code is a text generating function, that generates the next token given a seed text. I have used this code from multiple online lectures, but most of those videos were outdated, so they still used the predict_classes method.
Here is the error I was receiving: Error in Code
I have tried a couple of solutions but none of them worked. For one, I used the .predict() method directly but I was not getting the correct answer.
I also tried the following code as well:
def generate_text_seq(model, tokenizer, text_seq_length, seed_text, n_words):
text = []
for _ in range(n_words):
encoded = tokenizer.texts_to_sequences([seed_text])[0]
encoded = pad_sequences([encoded], maxlen = text_seq_length, truncating = 'pre')
pred_y = model.predict(encoded)
y_pred = np.argmax(pred_y, axis = 1)
predicted_word = ''
for word, index in tokenizer.word_index.items():
if index == y_pred:
predicted_word = word
break
seed_text = seed_text + ' ' + predicted_word
text.append(predicted_word)
return ' '.join(text)