如何将单词的keras tokenizer.texts_to_matrix(单热编码矩阵)转换回文本

How to convert keras tokenizer.texts_to_matrix (one-hot encoded matrix) of words back to text

我提到了这个 post,它讨论了如何使用 reverse_map 策略从 keras 中标记器的 text_to_sequences 函数取回文本。

我想知道 text_to_matrix 函数是否有取回文本的函数。

示例:

from tensorflow.keras.preprocessing.text import Tokenizer

docs = ['Well done!',
    'Good work',
    'Great effort',
    'nice work',
    'Excellent!']

# create the tokenizer
t = Tokenizer()

# fit the tokenizer on the documents
t.fit_on_texts(docs)
print(t)
encoded_docs = t.texts_to_matrix(docs, mode='count')
print(encoded_docs)
print(t.word_index.items())

Output: 
<keras_preprocessing.text.Tokenizer object at 0x7f746b6594e0>
[[0. 0. 1. 1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 1. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1.]]
dict_items([('work', 1), ('well', 2), ('done', 3), ('good', 4), ('great', 5), ('effort', 6), 
('nice', 7), ('excellent', 8)])

如何从单热矩阵取回文档?

如果您只需要文字,您可以按以下方式轻松完成。

import numpy as np
import pandas as pd
r, c = np.where(encoded_docs>=1)
res = pd.DataFrame({'row':r, 'col':c})
res["col"] = res["col"].map(t.index_word)
res = res.groupby('row').agg({'col':lambda x: x.str.cat(sep=' ')})

但是如果你需要订单,你不能。在你进入词袋表示的那一刻,你就失去了文档中单词的顺序。

对于预测而不是给出的one-hot矩阵,我想出了以下解决方案:

def onehot_to_text (mat,tokenizer, cutoff):
    mat = pd.DataFrame(mat)
    mat.rename(columns=tokenizer.index_word, inplace=True)
    output = mat.sum(axis=1)
    for row in range(mat.shape[0]):
       if output[row] == 0:
          output[row] = []
       else:
          output[row] = mat.columns[mat.iloc[row,:] >= cutoff].tolist()
   return(output)

onehot_to_text(encoded_docs,t, 0.5)给出相应的文本列表。

此函数可以处理全为零的行。