【问题标题】:One Hot Encoding for representing corpus sentences in python一种在python中表示语料库句子的热编码
【发布时间】:2015-08-02 09:01:50
【问题描述】:

我是 Python 和 Scikit-learn 库的初学者。 我目前需要从事一个 NLP 项目,该项目首先需要通过 One-Hot Encoding 表示一个大型语料库。 我已经阅读了 Scikit-learn 关于预处理的文档。OneHotEncoder,但是,这似乎不是我对术语的理解。

基本上,思路类似如下:

  • 1000000 周日; 0100000 星期一; 0010000 星期二; ... 0000001 星期六;

如果语料库只有 7 个不同的单词,那么我只需要一个 7 位向量来表示每个单词。然后,一个完整的句子可以用所有向量的合取来表示,它是一个句子矩阵。 但是,我在Python中尝试过,它似乎不起作用......

我该如何解决这个问题?我的语料库中有大量不同的词。

顺便说一句,如果向量大部分都是零,我们可以使用 Scipy.Sparse 来缩小存储空间,例如 CSR。

因此,我的整个问题将是:

语料库中的句子如何用 OneHotEncoder 表示,并存储在 SparseMatrix 中?

谢谢你们。

【问题讨论】:

    标签: python machine-learning nlp scikit-learn one-hot-encoding


    【解决方案1】:

    为了使用 OneHotEncoder,您可以将文档拆分为标记,然后将每个标记映射到一个 id(对于同一个字符串,它总是相同的)。然后将 OneHotEncoder 应用于该列表。结果默认为稀疏矩阵。

    两个简单文档A BB B的示例代码:

    from sklearn.preprocessing import OneHotEncoder
    import itertools
    
    # two example documents
    docs = ["A B", "B B"]
    
    # split documents to tokens
    tokens_docs = [doc.split(" ") for doc in docs]
    
    # convert list of of token-lists to one flat list of tokens
    # and then create a dictionary that maps word to id of word,
    # like {A: 1, B: 2} here
    all_tokens = itertools.chain.from_iterable(tokens_docs)
    word_to_id = {token: idx for idx, token in enumerate(set(all_tokens))}
    
    # convert token lists to token-id lists, e.g. [[1, 2], [2, 2]] here
    token_ids = [[word_to_id[token] for token in tokens_doc] for tokens_doc in tokens_docs]
    
    # convert list of token-id lists to one-hot representation
    vec = OneHotEncoder(n_values=len(word_to_id))
    X = vec.fit_transform(token_ids)
    
    print X.toarray()
    

    打印(每个文档一个连接形式的热向量):

    [[ 1.  0.  0.  1.]
     [ 0.  1.  0.  1.]]
    

    【讨论】:

    • 谢谢!很有帮助!
    • 当 docs = ["AB", "BBC"] 时,您如何处理这种情况,例如处理不同的推文,它们并不总是具有相同的长度并包含不同的单词。跨度>
    • 一种常见的方法是设置最大长度并用填充字符填充较短的文本并切断较长的文本
    猜你喜欢
    • 2017-05-21
    • 2018-12-17
    • 2019-07-06
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多