我是Python和Scikit学习库的初学者。目前我需要做一个NLP项目,它首先需要用一个单一的热编码来表示一个大的语料库。我读过Scikit-学习关于preprocessing.OneHotEncoder的文档,然而,它似乎不是我的术语的理解。
基本上,这一想法类似于以下内容:
如果语料库只有7个不同的单词,那么我只需要一个7位向量来表示每个单词。然后,一个完整的句子可以用所有向量的连词来表示,这就是一个句子矩阵。然而,我试过用Python,它似乎不起作用.
我怎么才能解决这个问题?我的语料库里有很多不同的单词。
顺便说一句,如果向量大部分是用零实现的,我们可以使用Scipy.Sparse来使存储变得很小,例如,CSR。
因此,我的整个问题是:
语料库中的句子如何用OneHotEncoder表示,并存储在SparseMatrix中?
谢谢你们。
发布于 2015-05-21 00:21:25
为了使用OneHotEncoder,您可以将文档拆分为令牌,然后将每个令牌映射到id (对于相同的字符串总是相同)。然后将OneHotEncoder应用于该列表。结果在默认情况下是稀疏矩阵。
两个简单文档A B和B 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.]]https://stackoverflow.com/questions/30361118
复制相似问题