我参考了这篇文章,它讨论了如何使用reverse_map策略从keras中的tokenizer的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=' ')})
但如果你需要订单,你就不能。当你使用一袋单词表示时,你就会丢失文档中单词的顺序。
对于一个预测而不是给定的热矩阵,我提出了以下解决方案:
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(给出了相应的文本列表。
此函数可以处理全为零的行。