我们在进行一个数据挖掘项目,并使用了R语言中tm包的removeSparseTerms函数来减少文档词矩阵的特征。
然而,我们希望将代码移植到Python中。是否有sklearn、nltk或其他包中的函数可以提供相同的功能?
谢谢!
回答:
如果您的数据是纯文本,您可以使用CountVectorizer来完成这项工作。
例如:
from sklearn.feature_extraction.text import CountVectorizervectorizer = 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)
现在X
就是文档词矩阵。(如果您从事信息检索工作,您可能还需要考虑Tf-idf术语加权。)
它可以帮助您轻松地用几行代码获得文档词矩阵。
关于稀疏性 – 您可以控制以下参数:
- min_df – 文档词矩阵中允许的术语的最小文档频率。
- max_features – 文档词矩阵中允许的最大特征数
或者,如果您已经有了文档词矩阵或Tf-idf矩阵,并且您对什么是稀疏有概念,定义MIN_VAL_ALLOWED
,然后执行以下操作:
import numpy as npfrom scipy.sparse import csr_matrixMIN_VAL_ALLOWED = 2X = csr_matrix([[7,8,0], [2,1,1], [5,5,0]])z = np.squeeze(np.asarray(X.sum(axis=0) > MIN_VAL_ALLOWED)) #z是非稀疏术语 print X[:,z].toarray()#prints X without the third term (as it is sparse)[[7 8][2 1][5 5]]
(使用X = X[:,z]
以便X
保持为csr_matrix
。)
如果您希望设置最小文档频率的阈值,首先二值化矩阵,然后以相同的方式使用它:
import numpy as npfrom scipy.sparse import csr_matrixMIN_DF_ALLOWED = 2X = csr_matrix([[7, 1.3, 0.9, 0], [2, 1.2, 0.8 , 1], [5, 1.5, 0 , 0]])#Creating a copy of the dataB = csr_matrix(X, copy=True)B[B>0] = 1z = np.squeeze(np.asarray(X.sum(axis=0) > MIN_DF_ALLOWED))print X[:,z].toarray()#prints[[ 7. 1.3][ 2. 1.2][ 5. 1.5]]
在这个例子中,第三和第四个术语(或列)消失了,因为它们只出现在两个文档(行)中。使用MIN_DF_ALLOWED
来设置阈值。