Как преобразовать предсказанную последовательность обратно в текст в керасе?

У меня есть последовательность обучения, которая работает отлично и способна предсказать некоторые результаты. Проблема в том, что я понятия не имею, как преобразовать вывод обратно в текстовую последовательность.

Это мой код

from keras.preprocessing.text import Tokenizer,base_filter
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense

txt1="""What makes this problem difficult is that the sequences can vary in length,
be comprised of a very large vocabulary of input symbols and may require the model 
to learn the long term context or dependencies between symbols in the input sequence."""

#txt1 is used for fitting 
tk = Tokenizer(nb_words=2000, filters=base_filter(), lower=True, split=" ")
tk.fit_on_texts(txt1)

#convert text to sequence
t= tk.texts_to_sequences(txt1)

#padding to feed the sequence to keras model
t=pad_sequences(t, maxlen=10)

model = Sequential()
model.add(Dense(10,input_dim=10))
model.add(Dense(10,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])

#predicting new sequcenc
pred=model.predict(t)

#Convert predicted sequence to text
pred=??

4 ответа

Вы можете использовать прямо обратное tokenizer.sequences_to_texts функция.

text = tokenizer.sequences_to_texts(<list of the integer equivalent encodings>)

Я проверил выше, и это работает, как ожидалось.

PS: будьте особенно внимательны, чтобы аргумент был списком целочисленных кодировок, а не One Hot.

Вот решение, которое я нашел:

reverse_word_map = dict(map(reversed, tokenizer.word_index.items()))

Мне пришлось решить ту же проблему, и вот как я это сделал (вдохновлено обратным словарем @Ben Usemans).

# Importing library
from keras.preprocessing.text import Tokenizer

# My texts
texts = ['These are two crazy sentences', 'that I want to convert back and forth']

# Creating a tokenizer
tokenizer = Tokenizer(lower=True)

# Building word indices
tokenizer.fit_on_texts(texts)

# Tokenizing sentences
sentences = tokenizer.texts_to_sequences(texts)

>sentences
>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11, 12, 13]]

# Creating a reverse dictionary
reverse_word_map = dict(map(reversed, tokenizer.word_index.items()))

# Function takes a tokenized sentence and returns the words
def sequence_to_text(list_of_indices):
    # Looking up words in dictionary
    words = [reverse_word_map.get(letter) for letter in list_of_indices]
    return(words)

# Creating texts 
my_texts = list(map(sequence_to_text, sentences))

>my_texts
>[['these', 'are', 'two', 'crazy', 'sentences'], ['that', 'i', 'want', 'to', 'convert', 'back', 'and', 'forth']]

Вы можете сделать словарь, который отображает индекс обратно в символ.

index_word = {v: k for k, v in tk.word_index.items()} # map back
seqs = tk.texts_to_sequences(txt1)
words = []
for seq in seqs:
    if len(seq):
        words.append(index_word.get(seq[0]))
    else:
        words.append(' ')
print(''.join(words)) # output

>>> 'what makes this problem difficult is that the sequences can vary in length  
>>> be comprised of a very large vocabulary of input symbols and may require the model  
>>> to learn the long term context or dependencies between symbols in the input sequence '

Однако в этом вопросе вы пытаетесь использовать последовательность символов для прогнозирования вывода 10 классов, который не является последовательностью для модели последовательности. В этом случае вы не можете просто включить прогноз (или pred.argmax(axis=1)) вернуться к последовательности символов.

    p_test = model.predict(data_test).argmax(axis =1)

#Show some misclassified examples
misclassified_idx = np.where(p_test != Ytest)[0]
len(misclassified_idx) 
i= np.random.choice(misclassified_idx)
print((i))
print((df_test[i]))
print('True label %s Predicted label %s' , (Ytest[i], p_test[i]))

df_test is the original text
data_test is sequence of integer 
Другие вопросы по тегам