一个用于在python中表示语料库句子的热编码

Aar*_*Sun 2 python nlp machine-learning scikit-learn one-hot-encoding

我是Python和Scikit-learn库的先驱.我目前需要处理一个NLP项目,该项目首先需要通过One-Hot Encoding来表示大型语料库.我已经阅读了关于预处理的Scikit-learn的文档.但是,看起来它似乎不是我的术语的理解.

基本上,这个想法类似如下:

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

如果语料库只有7个不同的单词,那么我只需要一个7位数的向量来表示每个单词.然后,完成的句子可以由所有向量的连接表示,这是一个句子矩阵.但是,我在Python中试过,似乎没有用......

我该如何解决这个问题?我的语料库有很多不同的词.

顺便说一句,似乎如果向量大部分用零填充,我们可以使用Scipy.Sparse来使存储变小,例如CSR.

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

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

感谢你们.

ale*_*eju 5

为了使用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()
Run Code Online (Sandbox Code Playgroud)

打印(每个文档以连续形式显示一个热矢量):

[[ 1.  0.  0.  1.]
 [ 0.  1.  0.  1.]]
Run Code Online (Sandbox Code Playgroud)

  • 当docs = ["A B","BB C"]时,你如何处理这种情况,例如使用不同的推文,它们并不总是具有相同的长度并包含不同的单词. (5认同)