【问题标题】:How to convert keras tokenizer.texts_to_matrix (one-hot encoded matrix) of words back to text如何将单词的keras tokenizer.texts_to_matrix(单热编码矩阵)转换回文本
【发布时间】:2020-05-06 00:16:25
【问题描述】:

我参考了这篇文章,该文章讨论了如何使用 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)])

如何从 one-hot 矩阵中取回文档?

【问题讨论】:

    标签: python-3.x text keras tokenize one-hot-encoding


    【解决方案1】:

    如果你只想要单词,你可以很容易地做到这一点。

    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 编码器矩阵的特定行中的所有值都为零,则此代码无济于事。在这种情况下, res 返回的矩阵的行数少于父 one-hot 编码矩阵。有什么建议吗?
    【解决方案2】:

    对于预测而不是给出的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) 给出相应的文本列表。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2019-09-04
      相关资源
      最近更新 更多