【问题标题】:Equivalent of R's removeSparseTerms in Python [closed]Python中R的removeSparseTerms的等价物[关闭]
【发布时间】:2015-09-15 13:11:14
【问题描述】:

我们正在开展一个数据挖掘项目,并已使用 R 中 tm 包中的 removeSparseTerms 函数来减少文档术语矩阵的特征。

但是,我们希望将代码移植到 python。 sklearn、nltk 或其他包中是否有可以提供相同功能的功能?

谢谢!

【问题讨论】:

    标签: python r machine-learning scikit-learn tm


    【解决方案1】:

    如果您的数据是纯文本,您可以使用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

    它可以帮助您通过几行轻松获得文档术语矩阵。

    关于稀疏性 - 您可以控制这些参数:

    • min_df - 文档-词条矩阵中的词条允许的最小文档频率。
    • ma​​x_features - 文档术语矩阵中允许的最大特征数

    或者,如果您已经有了文档术语矩阵或 Tf-idf 矩阵,并且您有什么是稀疏的概念,请定义 MIN_VAL_ALLOWED,然后执行以下操作:

    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 设置阈值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-01
      • 2011-03-20
      • 2019-02-20
      • 1970-01-01
      • 2020-09-14
      • 2018-07-18
      • 2016-06-14
      • 2016-05-23
      相关资源
      最近更新 更多