3
我们正在研究一个数据挖掘项目,并在R中的tm包中使用removeSparseTerms函数来减少文档项矩阵的特征。R的removeSparseTerms在Python中的等效
但是,我们正在寻找将代码移植到python。在sklearn,nltk或其他一些可以提供相同功能的软件包中是否有函数?
谢谢!
我们正在研究一个数据挖掘项目,并在R中的tm包中使用removeSparseTerms函数来减少文档项矩阵的特征。R的removeSparseTerms在Python中的等效
但是,我们正在寻找将代码移植到python。在sklearn,nltk或其他一些可以提供相同功能的软件包中是否有函数?
谢谢!
如果您的数据是纯文本,您可以使用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)
现在X
是文档长期矩阵。 (如果你到信息检索您还想Tf–idf term weighting考虑
它可以帮助你用几行轻松搞定文档长期矩阵
关于稀疏性 - 你可以控制这些参数:。
或者,如果你已经有了文档长期矩阵或TF-IDF矩阵,和你有什么是稀疏的概念,定义MIN_VAL_ALLOWED
,然后做功能aximum号以下内容:
import numpy as np
from scipy.sparse import csr_matrix
MIN_VAL_ALLOWED = 2
X = csr_matrix([[7,8,0],
[2,1,1],
[5,5,0]])
z = np.squeeze(np.asarray(X.sum(axis=0) > MIN_VAL_ALLOWED)) #z is the non-sparse terms
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
。)
如果是最小文档频率你想设置一个门槛上,binarize矩阵第一,而且比用同样的方式:
import numpy as np
from scipy.sparse import csr_matrix
MIN_DF_ALLOWED = 2
X = csr_matrix([[7, 1.3, 0.9, 0],
[2, 1.2, 0.8 , 1],
[5, 1.5, 0 , 0]])
#Creating a copy of the data
B = csr_matrix(X, copy=True)
B[B>0] = 1
z = 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
来设置阈值。