我正在使用Python滑雪板库。我有150,000+句子。
我需要一个类似数组的对象,其中每一行对应一个句子,每一列对应一个单词,每个元素是该句子中的单词数。
例如:如果这两个句子是“狗跑”和“男孩跑”,我需要
[ [1, 1, 1, 0]
, [0, 1, 1, 1] ](列的顺序无关,并取决于分配给哪个词的列)
我的数组将是稀疏的(每个句子将包含可能单词的一小部分),所以我使用scipy.sparse。
def word_counts(texts, word_map):
w_counts = sp.???_matrix((len(texts),len(word_map)))
for n in range(0,len(texts)-1):
for word in re.findall(r"[\w']+", texts[n]):
index = word_map.get(word)
if index != None:
w_counts[n,index] += 1
return w_counts
...
nb = MultinomialNB() #from sklearn
words = features.word_list(texts)
nb.fit(features.word_counts(texts,words), classes)我想知道稀疏矩阵是最好的。
我试过使用coo_matrix,但得到了一个错误:
TypeError: coo_matrix对象没有属性“__getitem__”
我查看了COO的文档,但是被下面的弄糊涂了
稀疏矩阵可用于算术运算。 COO格式的缺点..。不直接支持:算术操作
我使用了dok_matrix,这起作用了,但我不知道这在这种情况下是否表现最好。
提前谢谢。
发布于 2012-11-08 17:22:07
尝试lil_matrix或dok_matrix;它们易于构造和检查(但在lil_matrix的情况下,可能非常慢,因为每次插入都需要线性时间)。接受稀疏矩阵的学习估计器将接受任何格式,并在内部将它们转换成有效的格式(通常是csr_matrix)。您也可以使用tocoo、todok、tocsr等方法对scipy.sparse矩阵进行转换。
或者,只需使用scikit提供的CountVectorizer或DictVectorizer类就可以达到这个目的。CountVectorizer将整个文档作为输入:
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> documents = ["The dog ran", "The boy ran"]
>>> vectorizer = CountVectorizer(min_df=0)
>>> vectorizer = CountVectorizer(min_df=0, stop_words=[])
>>> X = CountVectorizer.fit_transform(documents)
>>> X = vectorizer.fit_transform(documents)
>>> X.toarray()
array([[0, 1, 1, 1],
[1, 0, 1, 1]])..。虽然DictVectorizer假设您已经完成了标记化和计数,但是每个示例的dict中都有这样的结果:
>>> from sklearn.feature_extraction import DictVectorizer
>>> documents = [{"the":1, "boy":1, "ran":1}, {"the":1, "dog":1, "ran":1}]
>>> X = vectorizer.fit_transform(documents)
>>> X.toarray()
array([[ 1., 0., 1., 1.],
[ 0., 1., 1., 1.]])
>>> vectorizer.inverse_transform(X[0])
[{'ran': 1.0, 'boy': 1.0, 'the': 1.0}]( min_df参数添加到CountVectorizer是几个版本前添加的。如果您使用的是旧版本,请省略它,或者更确切地说,升级。)
编辑根据常见问题,我必须披露我的归属,所以这里说:我是DictVectorizer的作者,我也写了一些CountVectorizer。
https://stackoverflow.com/questions/13294254
复制相似问题