机器学习——用python表示语料库句子的一个热门编码



我是Python和Scikit-learn库的初学者。我目前需要在一个NLP项目上工作,该项目首先需要通过One-Hot编码表示一个大型语料库。我已经阅读了Scikit-learn关于预处理的文档。OneHotEncoder,然而,它似乎不是我的术语的理解。

基本思路如下:

  • 1000000周日;周一0100000;周二0010000;…0000001周六;

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

我怎样才能解决这个问题?我的语料库中有大量不同的单词。

顺便说一句,如果向量大部分都是0,我们可以使用Scipy。稀疏使存储空间变小,例如CSR。

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

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

谢谢大家

为了使用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.]]

最新更新