gpt4 book ai didi

python - NumPy 还是字典?

转载 作者:太空狗 更新时间:2023-10-29 23:58:33 24 4
gpt4 key购买 nike

我必须处理大型数据集。我需要存储每个句子的词频;我可以使用字典列表或使用 NumPy 数组来完成。

但是,我将不得不排序和追加(以防单词已经存在)- 在这种情况下哪个更好?

最佳答案

您描述的问题的解决方案是 scipy's sparse matrix .

一个小例子:

from scipy.sparse import csr_matrix
docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
indptr = [0]
indices = []
data = []
vocabulary = {}
for d in docs:
for term in d:
index = vocabulary.setdefault(term, len(vocabulary))
indices.append(index)
data.append(1)
indptr.append(len(indices))

print csr_matrix((data, indices, indptr), dtype=int).toarray()

每个句子是行,每个术语是一列。

另一个提示 - 查看 CountVectorizer :

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=2)
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?',
]
vectorizer = vectorizer.fit(corpus)
print vectorizer.vocabulary_
#prints {u'this': 4, u'is': 2, u'the': 3, u'document': 0, u'first': 1}
X = vectorizer.transform(corpus)

print X.toarray()
#prints
[[1 1 1 1 1]
[1 0 1 1 1]
[0 0 0 1 0]
[1 1 1 1 1]]

现在 X 是您的文档术语矩阵(注意 X 是 csr_matrix)。您也可以使用 TfidfTransformer如果你想 tf-idf 它。

关于python - NumPy 还是字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31202124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com